如何使用java搜索/查找JSON

我有一个下面的JSON字符串,我想在JSON字符串中找到/搜索条件。

1)。 查找存在的键数。 2)。 获取给定键的值(如果我们有数组)

{ "store": { "book": [ { "category": "reference", "author": "Nigel Rees", "title": "Sayings of the Century", "price": 8.95 }, { "category": "fiction", "author": "Evelyn Waugh", "title": "Sword of Honour", "price": 12.99 }, { "category": "fiction", "author": "Herman Melville", "title": "Moby Dick", "isbn": "0-553-21311-3", "price": 8.99 }, { "category": "fiction", "author": "JRR Tolkien", "title": "The Lord of the Rings", "isbn": "0-395-19395-8", "price": 22.99 } ], "bicycle": { "color": "red", "price": 19.95 } }, "expensive": 10 } 

我正在寻找像Groovy GPath Syntax这样的解决方案

  • store.book – 此数组的大小。
  • store.book [*] .category – 数组中密钥的出现次数。
  • store.bicycle – 如果发现它必须返回true值

您还可以使用REST Assured提供的JsonPath项目。 此JsonPath项目使用Groovy GPath表达式。 在Maven你可以这样依赖它:

  com.jayway.restassured json-path 2.4.0  

例子:

要获取所有图书类别的列表:

 List categories = JsonPath.from(json).get("store.book.category"); 

获得第一本书类别:

 String category = JsonPath.from(json).get("store.book[0].category"); 

获取最后一本书类别:

 String category = JsonPath.from(json).get("store.book[-1].category"); 

获取价格在5到15之间的所有书籍:

 List books = JsonPath.from(json).get("store.book.findAll { book -> book.price >= 5 && book.price <= 15 }"); 

GPath非常强大,您可以在路径表达式中使用更高阶函数和所有Groovy数据结构。

首先,您必须添加依赖项

  org.json json 20090211  

然后你可以使用这段代码:

 import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.json.XML; public class Main { public static int PRETTY_PRINT_INDENT_FACTOR = 4; public static String TEST_XML_STRING = "TransEndDate20170731Failed ReasonOperator 03058361178\03058365278 has no permission to perform the Check Balance service.TransEndTime12361120000S_X20130129210125Initiator authentication error.000749213589AG_20170731_00004c28e51f1f822e9e"; public static void main(String[] args) { try { JSONObject xmlJSONObj = XML.toJSONObject(TEST_XML_STRING); String jsonPrettyPrintString = xmlJSONObj.toString(PRETTY_PRINT_INDENT_FACTOR); System.out.println(jsonPrettyPrintString); System.out.println("Element="+xmlJSONObj.getJSONObject("Result").getInt("ResultCode")); } catch (JSONException je) { System.out.println(je.toString()); } } } // in it i am searching an element which is present in a json object