如何从jsonarray读取值?

时间:2013-10-01 11:22:15

标签: java json

这是Json文件。

{
  "paging": {
    "next_offset": 100,
    "total": 247,
    "limit": 100
  },
  "body_stats": [
    {
      "weight": 208.0,
      "id": "13500547638911",
      "date": "2012-10-     12T15:12:50Z",
      "user_id": "13499829320503",
      "bmr": 2723.328,
      "bmi": 28.2067901234568
    },
    {
      "resting_heart_rate": 65.0,
      "weight": 135.0,
      "id": "1b5kegg00     00js2p5pfmg000000",
      "date": "2013-04-     15T00:44:12Z",
      "user_id": "13589643116210",
      "girths": {
        "abdomen": 30.0,
        "waist": 30.0
      }
    }
  ]
}

我想从这个json中读取值,

try{
       Object obj = parser.parse(new FileReader("D:/jdemo.json"));
       JSONObject jsonObject = (JSONObject) obj; 
       JSONArray companyList = (JSONArray)jsonObject.get("body_stats");
       Iterator<Object> iterator = companyList.iterator();
       while (iterator.hasNext()) {
           System.out.println(iterator.next());
       } 
}

输出:

{
  "id": "13500547638911",
  "bmr": 2723.328,
  "weight": 208.0,
  "bmi": 28.2067901234568,
  "user_id": "13499829320503",
  "date": "2012-10-12T15:12:50Z"
},
{
  "id": "1b5kegg0000js2p5pfmg000000",
  "weight": 135.0,
  "girths": {
    "abdomen": 30.0,
    "waist": 30.0
  },
  "user_id": "13589643116210",
  "date": "2013-04-15T00:44:12Z",
  "resting_heart_rate": 65.0
}

但我想从这里读取"girths"{" ",""}如何阅读girths{}值?

3 个答案:

答案 0 :(得分:1)

这是一种方法。

JsonElement jsonElement = new JsonParser().parse(new FileReader("D:/jdemo.json"));
JsonObject  jsonObject  = jsonElement.getAsJsonObject();
JsonArray   jsonArray   = jsonObject.getAsJsonArray("body_stats");

 for(JsonElement body_stats : jsonArray) {
     JsonElement girths = body_stats.getAsJsonObject().get("girths");
     if(griths !=null) {
          //The logic
     }
  }

答案 1 :(得分:0)

"girths"应该是另一个JSONObject,所以我想

.getJSONObject(2).get("girths");

JSONArray

答案 2 :(得分:0)

try{
       Object obj = parser.parse(new FileReader("D:/jdemo.json"));
       JSONObject jsonObject = (JSONObject) obj; 
       JSONArray companyList = (JSONArray)jsonObject.get("body_stats");
       Iterator<JSONObject> iterator = companyList.iterator();
       while (iterator.hasNext()) {
              JSONObject  jsonObject = iterator.next();
              Object  object = jsonObject.get("girths");
              if(object != null){
                   JSONObject  girths = (JSONObject )object ;
                   System.out.println(girths);
              }
       } 
}
相关问题