我刚开始探索JsonPath。我想探索的不仅仅是可以做些什么,还有一些有效的策略。
例如,假设我必须遍历json字符串中一个元素中包含的数组。
我正在使用https://github.com/jayway/JsonPath#path-examples中的“商店”示例。
为了获得书本本身,我想我可以这样做:
List<?> allBooks = JsonPath.<List<?>>read(context, "$.store.book");
以这种方式思考是否有意义?
这是迭代这个我不确定的逻辑。
我原本以为我可以定义一个“Book”pojo然后做这样的事情:
for (int ctr = 0; ctr < allBooks.size(); ++ ctr) {
Book book = JsonPath.<Book>read(context, ".[" + ctr + "]");
System.out.println("book[" + book + "]");
}
然而,这不起作用。此时“read
”方法会返回JSONArray
。
https://github.com/jayway/JsonPath#what-is-returned-when的代码示例中的最后一行接近我正在查看的内容,但这需要在每次迭代中解析json。看起来“DocumentContext
”类的“read
”方法可以采用类型参数,但不能使用“JsonPath
”。
有什么合理的策略来导航这样的东西?
答案 0 :(得分:2)
JSON路径只会返回一个Maps
列表,因为您已经看过了。您需要一种方法来告诉它如何将这些值映射到对象 - 为此您需要自定义配置。还有像Gson等其他提供商,但我只使用过杰克逊。
Configuration configuration = Configuration
.builder()
.jsonProvider(new JacksonJsonProvider())
.mappingProvider(new JacksonMappingProvider())
.build();
第二步是使用TypeRef
指定泛型类型信息,并在读取标记时将其传递。
List<Book> allBooks = JsonPath.using(configuration)
.parse(context)
.read("$.store.book", new TypeRef<List<Book>>() {});
结果你得到了一个很好的Book
个对象列表。