在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