【问题标题】:Parsing Nested JSON Array with json-simple [duplicate]使用 json-simple 解析嵌套的 JSON 数组 [重复]
【发布时间】:2016-02-19 01:53:03
【问题描述】:

尝试使用 json simple 来解析来自 rest 服务的数据。响应如下:

{
   "locations": [
      "city" : "San Jose",
      "state" : "Ca",
    "job" : {
      "site" : "Main Processing",
      "region" : "USA"
    }
  ]
}
JSONParser jsonParser = new JSONParser();
JSONObject jsonObject = (JSONObject) jsonParser.parse(reader);

JSONArray array = (JSONArray) jsonObject.get("locations");

for(int i = 0; i < array.size(); i++) {
 String site = array.getJSONObject(i).getString("site");
}

我的问题是我无法从 JSONArray 对象中获取对作业元素的引用。 “位置”引用是基本解析,但“工作”引用在数组中定义时给了我问题。

getJSONObject 似乎也不是 JSONArray 的有效方法。

这可以用 json-simple 库来完成吗?

【问题讨论】:

  • 您显示的示例数据完全无效。 JSON 规范不允许不带引号的字符串键,或将键值对作为数组成员,或在键值对之间省略逗号。
  • 错字,添加了正确的 JSON 响应。
  • 仍然无效,因为locations数组中有键值对。

标签: java json json-simple


【解决方案1】:

getJSONObject 方法由org.json.JSONArray 类提供。 (不使用 json-simple)。我在 json-simple 文档中找不到它。所以使用org.json.*包导入,你可以这样做:

JSONObject jsonObject = new JSONObject(jsonAsString);
JSONArray array = jsonObject.getJSONArray("locations");

//You should check that array.length() >= 3
JSONObject job = array.getJSONObject(2);
String site = job.getString("site");

【讨论】:

  • 这无法获取“站点”标签数据。得到一个错误基本上说元素不存在。是否有专门处理嵌套对象的 json 库?
  • 是的。但是我的代码是错误的。我更新了我的答案。
猜你喜欢
  • 1970-01-01
  • 2015-06-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多