简体   繁体   中英

get JsonObject without knowing its name Java

I have this JSON I need to parse. Its format looks something likes this:

{
   "47M": [
           {
              "lat": 39.95507, 
              "lng": -75.152122, 
              "label": 8011, 
              "VehicleID": 8011, 
              "BlockID": 7995, 
              "Direction": "NorthBound", 
              "destination": "Spring Garden via 9th St.", 
              "Offset": 1, 
              "Offset_sec": 29
          }, 
          {
              "lat": 39.913765, 
              "lng": -75.155464, 
              "label": 8038, 
              "VehicleID": 8038, 
              "BlockID": 7993, 
              "Direction": "NorthBound", 
              "destination": "Spring Garden via 9th St.", 
              "Offset": 3, 
              "Offset_sec": 158
          }
     ]
} 

However, that "47M" can be "5", "H", "101", etc. And I need to get those "5", "H", etc. I believe I should use the loop for (obj : root) , but I don't know what's the type for obj

You could use simple json ( https://code.google.com/p/json-simple/ ) Library and code like this to iterate over the keys.

JSONParser parser = new JSONParser();

jObject = parser.parse(jsonString);
JSONObject jsonObject = (JSONObject) jObject;
for(Iterator iterator = jsonObject.keySet().iterator(); iterator.hasNext();) {
    String key = (String) iterator.next();
    System.out.println(jsonObject.get(key));
}

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