在JsonPath的典型使用情况下,库假定we know what to expect from a path:
就你而言,以上所有内容都没有关系,因为事先不知道类型,只需要结果作为JSON字符串。
JsonPath中的默认解析器太聪明了,会将所有东西都转换成好的LinkedHashMap对象;但如果使用JacksonJsonNodeJsonProvider,则会得到结果为JsonNode对象,并且您将从一个toString()
调用JSON字符串结果。
更好的是,您可以使用JsonPath optionALWAYS_RETURN_LIST
,这意味着您不必担心路径是确定的还是无限的(无论您的结果是单个对象还是列表)。
// Example from https://github.com/jayway/JsonPath#path-examples
final String json = "{\"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\": \"J. R. R. Tolkien\",\"title\": \"The Lord of the Rings\",\"isbn\": \"0-395-19395-8\",\"price\": 22.99}],\"bicycle\": {\"color\": \"red\",\"price\": 19.95}},\"expensive\": 10}";
Configuration conf = Configuration.builder().jsonProvider(new JacksonJsonNodeJsonProvider())
.options(Option.ALWAYS_RETURN_LIST, Option.SUPPRESS_EXCEPTIONS).build();
ArrayNode node = JsonPath.using(conf).parse(json).read("$.store.book[*]"); // indefinite
for (Object o : node) {
System.out.println(o.toString());
}
// {"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":"J. R. R. Tolkien","title":"The Lord of the Rings","isbn":"0-395-19395-8","price":22.99}
node = JsonPath.using(conf).parse(json).read("$.store.book[0].author"); // definite
for (Object o : node) {
System.out.println(o.toString());
}
// "Nigel Rees"
如果你获得了字符串(大概JSON字符串)的列表,你会尝试将其解析为对象呢? – approxiblue
我会把它们解析成字符串。我输出到一个文本文件,所以字符串将是最容易处理。 – Adam