JSONPath在Java中的基本用法

时间:2014-06-25 15:14:44

标签: java json jsonpath

我将JSON作为字符串,将JSONPath作为字符串。我想用JSON路径查询JSON,将生成的JSON作为字符串。

我收集了Jayway's json-path is the standard。但是,online APIactual library you get from Maven没有多大关系。 GrepCode's version大致匹配。

似乎我应该能够做到:

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

问题是read根据JSONPath实际发现的内容(例如List<Object>Stringdouble等)返回最合适的内容,因此我的代码会为某些查询抛出异常。假设有一些方法可以查询JSON并获取JSON,这似乎是合理的。有什么建议吗?

4 个答案:

答案 0 :(得分:11)

肯定有一种方法可以查询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);

以上的输出将是内部Json。

  

[{ “POSTAL_CODE”:{ “区”: “Ghaziabad的”, “针”:201001 “pre_paid”: “Y”, “现金”: “Y”, “拾取”: “Y”,“REPL “:” N”, “鳕鱼”: “Y”, “is_oda”: “N”, “sort_code”: “GB”, “STATE_CODE”: “UP”}}]

现在可以通过迭代我们上面的List(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 );
}

输出将是:

  

pin :: 201001 district :: Ghaziabad

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

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

答案 1 :(得分:7)

jayway JsonPath找到的Java JsonPath API可能会因为上述所有答案/评论而有所改变。文档也是。只需按照上面的链接阅读README.md,它包含一些非常明确的使用文档IMO。

基本上,截至目前最新版本的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);

供参考,调用&#39; JsonPath.parse(..)&#39;将返回班级的对象&#39; JsonContent&#39;实现一些接口,例如&#39; ReadContext&#39;,其中包含几个不同的读取(..)&#39;操作,例如上面演示的操作:

/**
 * 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);

希望这对任何人都有帮助。

答案 2 :(得分:0)

对于那些想知道为什么其中一些古老的答案不起作用的人,您可以从test cases中学到很多东西。

截至2018年9月,这是获取Jackson JsonNode结果的方法:

Configuration jacksonConfig = Configuration.builder()
                              .mappingProvider( new JacksonMappingProvider() )
                              .jsonProvider( new JacksonJsonProvider() )
                              .build();

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

答案 3 :(得分:-1)

查看jpath API。它是JSON Data的xpath等价物。您可以通过提供将遍历JSON数据并返回请求值的jpath来读取数据。

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

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

自述 -

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