Json转对象的简单例子

 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        //转圈
        progressDialog = new ProgressDialog(this);
        progressDialog.show();
        
        //开启子线程请求数据
        new Thread(){
            @Override
            public void run() {
                
                try {
                    //请求数据
                    URL url = new URL(path);
                    //httpurlConnection 
                    HttpURLConnection con = (HttpURLConnection) url.openConnection();
                    //设置请求信息
                    con.setRequestMethod("GET");
                    con.setConnectTimeout(timeout);
                    //得到请求的状态码
                    int status = con.getResponseCode();
                    //得到输入流
                    InputStream inputStream = con.getInputStream();
                    //创建输出流
                    ByteArrayOutputStream os = new ByteArrayOutputStream();
                    //OK
                    if (status == 200) {
                    
                        int len = 0;
                        byte[] buffer = new byte[1024];
                        //循环获取数据
                        while((len=inputStream.read(buffer))>0) {
                            os.write(buffer, 0, len);
                        }
                        //转化数据类型
                        String data = os.toString();
                        //打印数据

//                      
//                      //转化数据格式
                        JSONObject ob = new JSONObject(data);
                        JSONArray arr = ob.getJSONArray("datas");
                        System.out.println(ob.get("total").toString());
                        Log.e("datta", ob.get("total").toString()+"=========================================");
                        Log.e("haha", ob.toString()+"==============================================");
                        
                        
                    }
                    //关闭流
                    os.close();
                    inputStream.close();
                    //停止
                    progressDialog.dismiss();
                } catch (Exception e) {
                    // TODO Auto-generated catch block
//                  e.printStackTrace();
                    //停止
                    progressDialog.dismiss();
                    
                    Log.e("出错了", e.getMessage()+"error11111");
                    
                    
                }
            };
            
        }.start();
    }

你可能感兴趣的:(Json转对象的简单例子)