JSON 解析

1.android中json数据的解析一般来所分为两步

  1)第一步先从网络获取json格式的字符串

  2)第二步解析json数据

  

  

1.JSON解析
     (1).解析Object之一:

  解析方法:

1
2
JSONObject demoJson = new JSONObject(jsonString);
String url = demoJson.getString("url");

  (2).解析Object之二:

1
{"name":"android","name":"iphone"}

  解析方法:

1
2
3
4
JSONObject demoJson = new JSONObject(jsonString);
String name = demoJson.getString("name");
String version = demoJson.getString("version");
System.out.println("name:"+name+",version:"+version);

     (3).解析Array之一:

1
{"number":[1,2,3]}

   解析方法:

1
2
3
4
5
6
JSONObject demoJson = new JSONObject(jsonString);
JSONArray numberList = demoJson.getJSONArray("number");
for(int i=0; i<numberList.length(); i++){
    //因为数组中的类型为int,所以为getInt,其他getString,getLong同用
    System.out.println(numberList.getInt(i));
}

  (4).解析Array之二:

1
{"number":[[1],[2],[3]]}

  解析方法:

1
2
3
4
5
6
7
//嵌套数组遍历
JSONObject demoJson = new JSONObject(jsonString);
JSONArray numberList = demoJson.getJSONArray("number");
for(int i=0; i<numberList.length(); i++){
      //获取数组中的数组
      System.out.println(numberList.getJSONArray(i).getInt(0));
}

  (5).解析Object和Array:

1
{"mobile":[{"name":"android"},{"name":"iphone"}]}

  解析方法:

1
2
3
4
5
JSONObject demoJson = new JSONObject(jsonString);
JSONArray numberList = demoJson.getJSONArray("mobile");
for(int i=0; i<numberList.length(); i++){
      System.out.println(numberList.getJSONObject(i).getString("name"));
}

 /**  
         * 获取"数组形式"的JSON数据,  
         * @param path  网页路径  
         * @return  返回JSONArray  
         * @throws Exception  
          */  
        public static String getJSONArray(String path) throws Exception {
                String json = null;
                URL url = new URL(path);
                // 利用HttpURLConnection对象,我们可以从网络中获取网页数据.
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                // 单位是毫秒,设置超时时间为5秒
                conn.setConnectTimeout(5 * 1000);
                // HttpURLConnection是通过HTTP协议请求path路径的,所以需要设置请求方式,可以不设置,因为默认为GET
                conn.setRequestMethod("GET");
                if (conn.getResponseCode() == 200) {// 判断请求码是否是200码,否则失败
                        
                        InputStream is = conn.getInputStream(); // 获取输入流
                        byte[] data = readStream(is); // 把输入流转换成字符数组
                        json = new String(data); // 把字符数组转换成字符串
//                        JSONArray jsonArray = new JSONArray(json);// 用android提供的框架JSONArray读取JSON数据,转换成Array
                }
                return json;
        }

     JSONArray jsonArray = new JSONArray(carIdJSON);
                                        for (int i = 0; i < jsonArray.length(); i++) {
                                                JSONObject jsonObject = jsonArray.getJSONObject(i);
    jsonObject.getString("carNo");
    jsonObject.getString("ID");

                                        }

原文地址:https://www.cnblogs.com/zhanglanyun/p/2711396.html