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>