您的位置:首页 > 理论基础 > 计算机网络

获取网络Json格式数据-使用原生态解析Json

2017-02-18 18:13 856 查看
Activity:
在Ativity中写个方法
public void parsejson(View view) {
new MyTask().execute();
}



class MyTask extends AsyncTask {
@Override
protected Object doInBackground(Object[] params) {
try {
URL url = new URL("http://192.168.42.58:8080/examples/person.json");
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("GET");
httpURLConnection.setConnectTimeout(5000);
//获取结果码
int code = httpURLConnection.getResponseCode();
if (code == 200) {
InputStream is = httpURLConnection.getInputStream();
//测试
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(is));
String str = null;
StringBuffer stringBuffer = new StringBuffer();
while ((str = bufferedReader.readLine()) != null) {
stringBuffer.append(str);}
Log.i("test", stringBuffer.toString());
//解析Json,
//1.原生态代码解析
JSONObject jsonObject = new JSONObject(stringBuffer.toString());
int list=jsonObject.getInt("list");
Log.i("test","长度"+list);

JSONArray jsonArray=jsonObject.getJSONArray("persons");
for (int i=0;i<jsonArray.length();i++) {
JSONObject object = jsonArray.getJSONObject(i);
int pid = object.getInt("pid");
String pname = object.getString("pnae");
int page = object.getInt("page");
Log.i("test", pid + pname + page);
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();}
return null;
}
@Override
protected void onPostExecute(Object o) {
super.onPostExecute(o);
}}


在配置文件中加一个网络权限

<uses-permission android:name="android.permission.INTERNET"></uses-permission>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐