1

我目前在 Java 中使用 json-simple 库来处理 JSON 对象。大多数时候,我从一些外部 Web 服务获取 JSON 字符串,需要对其进行解析和遍历。即使对于一些不太复杂的 JSON 对象,可能需要很长时间的打字练习。

假设我得到以下字符串作为 responseString:

{
  "employees": [
    {
      "firstName": "John",
      "lastName": "Doe"
    },
    {
      "firstName": "Anna",
      "lastName": "Smith"
    },
    {
      "firstName": "Peter",
      "lastName": "Jones"
    }
  ],
  "title": "some company",
  "headcount": 3
}

要获得 3d 员工的姓氏,我必须:

JSONObject responseJson = (JSONObject) JSONValue.parse(responseString);
JSONArray employees = (JSONArray) responseJson.get("employees");
JSONObject firstEmployee = (JSONObject) employees.get(0);
String lastName = (String) firstEmployee.get("lastName");

至少是这样的。在这种情况下不会太长,但可能会变得复杂。

我有什么办法(也许切换到其他 Java 库?)让更流线型的流利方法工作?

String lastName = JSONValue.parse(responseString).get("employees").get(0).get("lastName")

我想不出这里有任何自动投射方法,所以会很感激任何想法。

4

1 回答 1

1

试试 Groovy JsonSlurper

println new JsonSlurper().parseText(json).employees[0].lastName

输出:

Doe

但最好的解决方案是JsonPath - 输入

String name = JsonPath.parse(json).read("$.employees[0].lastName", String.class);
System.out.println(name);
于 2015-09-16T19:09:13.577 回答