在java中查询一个JSONObject [英] Query a JSONObject in java
问题描述
我想知道是否在某个地方存在能够查询 JSONObject 的 Java 库.更深入地,我正在寻找类似的东西:
I was wondering if somewhere out there exists a java library able to query a JSONObject. In more depth I'm looking for something like:
String json = "{ data: { data2 : { value : 'hello'}}}";
...
// Somehow we managed to convert json to jsonObject
...
String result = jsonObject.getAsString("data.data2.value");
System.out.println(result);
我希望得到hello"作为输出.
I expect to get "hello" as output.
到目前为止,我找到的最快的方法是使用 Gson:
So far, the fastest way I have found is using Gson:
jsonObject.getAsJsonObject("data").getAsJsonObject().get("data2").getAsJsonObject("value").getAsString();
编写和阅读实际上并不容易.有什么更快的吗?
It's not actually easy to write and read. Is there something faster?
推荐答案
我刚刚意外地发现了一个非常有趣的项目:JSON 路径
I've just unexpectedly found very interesting project: JSON Path
JsonPath 之于 JSON 就像 XPATH 之于 XML,这是一种提取给定文档部分的简单方法.
JsonPath is to JSON what XPATH is to XML, a simple way to extract parts of a given document.
有了这个库,您可以更轻松地完成您的要求,然后是我之前的建议:
With this library you can do what you are requesting even easier, then my previous suggestion:
String hello = JsonPath.read(json, "$.data.data2.value");
System.out.println(hello); //prints hello
希望这也能有所帮助.
这篇关于在java中查询一个JSONObject的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!