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

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


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

<uses-permission android:name="android.permission.INTERNET">uses-permission>

你可能感兴趣的:(获取网络Json格式数据-使用原生态解析Json)