1

这是 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{}值?

4

3 回答 3

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
     }
  }
于 2013-10-01T11:53:29.343 回答
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);
              }
       } 
}
于 2013-10-01T11:41:36.060 回答
0

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

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

在你的JSONArray

于 2013-10-01T11:29:59.767 回答