JSONObject與JSONArray 解析JSON格式字串

SecondDream_1017發表於2018-08-13

{

     "List":[

                {"age":20,"name":"0號"},

                {"age":21,"name":"1號"},

                {"age":22,"name":"2號"},

               {"age":23,"name":"3號"}

           ],

    "Data": {"address":"China","sex":"1","name":"jack","age":23}

}

=========================================================

JSONObject fromObject = JSONObject.fromObject(jsonStr);

//解析Object

JSONObject object = fromObject.getJSONObject("Data");

String string = object.getString("name");

int age = object.getInt("age");

String address = object.getString("address");

String sex = object.getString("sex");

//解析List

JSONArray jsonArray = fromObject.getJSONArray("List");

for(int i=0;i<jsonArray.size();i++){

       JSONObject obj = jsonArray.getJSONObject(i);

       String name = obj.getString("name");

       int ageN = obj.getInt("age");

       System.out.println(name+ageN);

}

 

###################################################################

###################################################################

List的JSON

[

     {"age":20,"name":"0號"},

     {"age":21,"name":"1號"},

     {"age":22,"name":"2號"},

     {"age":23,"name":"3號"}

]

//解析List

JSONArray jsonArray2 = JSONArray.fromObject(jsonStr);

for(int i=0;i<jsonArray2.size();i++){

      JSONObject obj = jsonArray2.getJSONObject(i);

      String name = obj.getString("name");

      int ageN = obj.getInt("age");

      System.out.println(name+ageN);

}

 

相關文章