Java中JSONPath的基本使用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24412511/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 12:04:21  来源:igfitidea点击:

Basic use of JSONPath in Java

javajsonjsonpath

提问by akroy

I have JSON as a string and a JSONPath as a string. I'd like to query the JSON with the JSON path, getting the resulting JSON as a string.

我有 JSON 作为字符串和 JSONPath 作为字符串。我想用 JSON 路径查询 JSON,将结果 JSON 作为字符串获取。

I gather that Jayway's json-pathis the standard. The online API, however, doesn't have have much relation to the actual library you get from Maven. GrepCode's versionroughly matches up though.

我认为Jayway 的 json-path是标准的. 在网上API,但是,并没有什么太大关系到你的Maven得到实际库不过,GrepCode 的版本大致匹配。

It seems like I ought to be able to do:

看起来我应该能够做到:

String originalJson; //these are initialized to actual data
String jsonPath;
String queriedJson = JsonPath.<String>read(originalJson, jsonPath);

The problem is that readreturns whatever it feels most appropriate based on what the JSONPath actually finds (e.g. a List<Object>, String, double, etc.), thus my code throws an exception for certain queries. It seems pretty reasonable to assume that there'd be some way to query JSON and get JSON back; any suggestions?

问题是,read什么感觉基于什么JSONPath真正的发现(例如,最合适的回报List<Object>Stringdouble等),因此我的代码会因某些查询的除外。假设有某种方法可以查询 JSON 并返回 JSON,这似乎很合理;有什么建议?

回答by Ankur Choudhary

There definitely exists a way to query Json and get Json back using JsonPath. See example below:

肯定存在一种查询 Json 并使用 JsonPath 取回 Json 的方法。请参阅下面的示例:

 String jsonString = "{\"delivery_codes\": [{\"postal_code\": {\"district\": \"Ghaziabad\", \"pin\": 201001, \"pre_paid\": \"Y\", \"cash\": \"Y\", \"pickup\": \"Y\", \"repl\": \"N\", \"cod\": \"Y\", \"is_oda\": \"N\", \"sort_code\": \"GB\", \"state_code\": \"UP\"}}]}";
 String jsonExp = "$.delivery_codes";
 JsonNode pincodes = JsonPath.read(jsonExp, jsonString, JsonNode.class);
 System.out.println("pincodesJson : "+pincodes);

The output of the above will be inner Json.

上面的输出将是内部 Json。

[{"postal_code":{"district":"Ghaziabad","pin":201001,"pre_paid":"Y","cash":"Y","pickup":"Y","repl":"N","cod":"Y","is_oda":"N","sort_code":"GB","state_code":"UP"}}]

[{"postal_code":{"district":"Ghaziabad","pin":201001,"pre_paid":"Y","cash":"Y","pickup":"Y","re​​pl":" N","cod":"Y","is_oda":"N","sort_code":"GB","state_code":"UP"}}]

Now each individual name/value pairs can be parsed by iterating the List (JsonNode) we got above.

现在可以通过迭代我们上面得到的列表(JsonNode)来解析每个单独的名称/值对。

for(int i = 0; i< pincodes.size();i++){
    JsonNode node = pincodes.get(i);
    String pin = JsonPath.read("$.postal_code.pin", node, String.class);
    String district = JsonPath.read("$.postal_code.district", node, String.class);
    System.out.println("pin :: " + pin + " district :: " + district );
}

The output will be:

输出将是:

pin :: 201001 district :: Ghaziabad

pin :: 201001 区 :: 加济阿巴德

Depending upon the Json you are trying to parse, you can decide whether to fetch a List or just a single String/Long value.

根据您尝试解析的 Json,您可以决定是获取 List 还是仅获取单个 String/Long 值。

Hope it helps in solving your problem.

希望它有助于解决您的问题。

回答by francois

Java JsonPath API found at jayway JsonPathmight have changed a little since all the above answers/comments. Documentation too. Just follow the above link and read that README.md, it contains some very clear usage documentation IMO.

由于上述所有答案/评论,在jayway JsonPath 上找到的 Java JsonPath API可能已经发生了一些变化。文档也是。只需点击上面的链接并阅读README.md,它包含一些非常清晰的 IMO 使用文档。

Basically, as of current latest version 2.2.0 of the library, there are a few different ways of achieving what's been requested here, such as:

基本上,从库的当前最新版本 2.2.0 开始,有几种不同的方法可以实现这里所要求的内容,例如:

Pattern:
--------
String json = "{...your JSON here...}";
String jsonPathExpression = "$...your jsonPath expression here..."; 
J requestedClass = JsonPath.parse(json).read(jsonPathExpression, YouRequestedClass.class);

Example:
--------
// For better readability:  {"store": { "books": [ {"author": "Stephen King", "title": "IT"}, {"author": "Agatha Christie", "title": "The ABC Murders"} ] } }
String json = "{\"store\": { \"books\": [ {\"author\": \"Stephen King\", \"title\": \"IT\"}, {\"author\": \"Agatha Christie\", \"title\": \"The ABC Murders\"} ] } }";
String jsonPathExpression = "$.store.books[?(@.title=='IT')]"; 
JsonNode jsonNode = JsonPath.parse(json).read(jsonPathExpression, JsonNode.class);

And for reference, calling 'JsonPath.parse(..)' will return an object of class 'JsonContent' implementing some interfaces such as 'ReadContext', which contains several different 'read(..)' operations, such as the one demonstrated above:

和作为参考,调用“JsonPath.parse(..)”将返回类“的一个目的JsonContent”实现一些接口,诸如“ ReadContext”,它包含几个不同的“读(..)的操作中,如一个表明以上:

/**
 * Reads the given path from this context
 *
 * @param path path to apply
 * @param type    expected return type (will try to map)
 * @param <T>
 * @return result
 */
<T> T read(JsonPath path, Class<T> type);

Hope this help anyone.

希望这可以帮助任何人。

回答by Satyajit Paul

Check out the jpath API. It's xpath equivalent for JSON Data. You can read data by providing the jpath which will traverse the JSON data and return the requested value.

查看 jpath API。它相当于 JSON 数据的 xpath。您可以通过提供将遍历 JSON 数据并返回请求值的 jpath 来读取数据。

This Java class is the implementation as well as it has example codes on how to call the APIs.

这个 Java 类是实现,它有关于如何调用 API 的示例代码。

https://github.com/satyapaul/jpath/blob/master/JSONDataReader.java

https://github.com/satyapaul/jpath/blob/master/JSONDataReader.java

Readme -

自述文件 -

https://github.com/satyapaul/jpath/blob/master/README.md

https://github.com/satyapaul/jpath/blob/master/README.md

回答by Hoobajoob

For those of you wondering why some of these years-old answers aren't working, you can learn a lot from the test cases.

对于那些想知道为什么这些多年以前的答案不起作用的人,您可以从测试用例中学到很多东西。

As of September 2018, here's how you can get Hymanson JsonNode results:

截至 2018 年 9 月,以下是获取 Hymanson JsonNode 结果的方法:

Configuration HymansonConfig = Configuration.builder()
                              .mappingProvider( new HymansonMappingProvider() )
                              .jsonProvider( new HymansonJsonProvider() )
                              .build();

JsonNode node = JsonPath.using( HymansonConfig ).parse(jsonString);