简体   繁体   中英

how to read values from jsonarray?

This is Json file.

{
  "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
      }
    }
  ]
}

I want to read values from this 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());
       } 
}

Output:

{
  "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
}

But I want to read "girths"{" ",""} from this how can I read girths{} value?

This is an approach.

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
     }
  }

"girths" should be another JSONObject , so I guess

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

on your JSONArray

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);
              }
       } 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM