获取网络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<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>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值