java 如何从 JSONObject 的路径中获取嵌套值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40783386/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I get a nested value in a JSONObject from its path?
提问by PLNech
I'm trying to implement a function that given any JSONObject
and a path String
, would return the object's attribute corresponding to the path.
我正在尝试实现一个给定 anyJSONObject
和 path的函数String
,它将返回与路径对应的对象的属性。
For example, given this json:
例如,给定这个 json:
{
"name": "John",
"friends": [
{"name": "Paul",
"age":42},
{"name": "Peter",
"age":24}
],
"address": {"city": "London"}
}
getAttribute(jsonObject, "name")
should return"John"
getAttribute(jsonObject, "address.city")
should return"London"
getAttribute(jsonObject, "friends[0].name")
should return"Paul"
getAttribute(jsonObject, "name")
应该回来"John"
getAttribute(jsonObject, "address.city")
应该回来"London"
getAttribute(jsonObject, "friends[0].name")
应该回来"Paul"
Note that this JSON is only an example, jsonObject
has no predefined structure and could represent any valid json.
请注意,此 JSON 只是一个示例,jsonObject
没有预定义的结构,可以表示任何有效的 json。
I wrote a first version implementing the first two cases, but handling arrays and multi-level arrays "foo[0][0].bar"
brings a lot of complexity to this function.
我写了一个实现前两种情况的第一个版本,但是处理数组和多级数组"foo[0][0].bar"
给这个函数带来了很多复杂性。
Is there a recommended tool/library/method for getting an attribute from a JSONObject given a "complex" path?
是否有推荐的工具/库/方法用于从给定“复杂”路径的 JSONObject 获取属性?
采纳答案by PLNech
the JSONPath standardby Stefan Goessner covers a more complex syntax, but it also handles the "classic javascript" JSON path syntax.
Stefan Goessner的JSONPath 标准涵盖了更复杂的语法,但它也处理“经典 javascript”JSON 路径语法。
Using JayWay's implementation for Java, it is trivial to answer the question:
使用JayWay 的 Java 实现,回答这个问题很简单:
public String getAttribute(JSONObject json, String path) {
return JsonPath.read(json.toString(), path);
}
回答by rares.urdea
If I understand your question correctly, you could have potentially already been answered here
如果我正确理解你的问题,你可能已经在这里得到了回答
Alternatively, you can also try the following open source library:
或者,您也可以尝试以下开源库:
回答by Krishnanunni P V
You can use GSON library and parse your json string to a POJO class.
您可以使用 GSON 库并将您的 json 字符串解析为 POJO 类。
private final static Gson GSON = new GsonBuilder().create();
public static <T> T fromJSON(String json, Class<T> clazz) {
try {
return GSON.fromJson(json, clazz);
} catch (JsonSyntaxException e) {
LOGGER.warn("Could not deserialize object", e);
}
return null;
}
Design your model class according to your JSON structure.
根据您的 JSON 结构设计您的模型类。