【问题标题】:get JsonObject without knowing its name Java在不知道名字的情况下获取 JsonObject Java
【发布时间】:2015-08-28 17:31:41
【问题描述】:

我有这个需要解析的 JSON。它的格式看起来像这样:

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

但是,“47M”可以是“5”、“H”、“101”等。我需要得到那些“5”、“H”等。 我相信我应该使用循环 for (obj : root) ,但我不知道 obj 的类型是什么

【问题讨论】:

  • 您使用的是哪个 JSON 库?
  • 把key转换成String可以吗,结果你想怎么用
  • 看来您可以根据您提供的示例假设 String。

标签: java json for-loop


【解决方案1】:

您可以使用简单的 json (https://code.google.com/p/json-simple/) 库和类似这样的代码来迭代键。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-01-23
    • 2016-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多