我目前在 Java 中使用 json-simple 库来处理 JSON 对象。大多数时候,我从一些外部 Web 服务获取 JSON 字符串,并且需要解析和遍历它。即使对于一些不太复杂的 JSON 对象来说,这也可能是相当长的输入练习。
假设我得到以下字符串作为响应字符串:
{
"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")
我在这里想不出任何自动转换方法,所以我会感激任何想法。
最佳答案
尝试 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);
关于java - 如何在Java中流畅地解析和遍历JSON对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32616607/