Java中JSONPath的基本使用

新手上路,请多包涵

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

我了解到 Jayway 的 json-path 是标准的.然而, 在线 API您从 Maven 获得的实际库 没有太大关系。 GrepCode 的版本 大致匹配。

看来我应该能够做到:

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

The problem is that read returns whatever it feels most appropriate based on what the JSONPath actually finds (eg a List<Object> , String , double 等),因此我的代码对某些查询抛出异常。假设有某种方法可以查询 JSON 并取回 JSON 似乎是很合理的;有什么建议么?

原文由 Cannoliopsida 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 971
1 个回答

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

作为参考,调用“JsonPath.parse(..)”将返回类“ JsonContent ”的对象,实现了一些接口,例如“ ReadContext ”,其中包含几个不同的“read(..)”操作,例如演示的以上:

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

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

原文由 franky duke 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题