[英]Strategies for iterating through JsonPath array
I just started exploring JsonPath today. 我今天才开始探索JsonPath。 I want to explore not just what's possible to do with it, but some effective strategies.
我不仅想探索使用它的可能性,还想探索一些有效的策略。
For instance, let's say I have to iterate through an array contained within one element in the json string. 例如,假设我必须遍历json字符串中一个元素内包含的数组。
I'm using the "store" example from https://github.com/jayway/JsonPath#path-examples . 我正在使用https://github.com/jayway/JsonPath#path-examples中的“商店”示例。
To get the list of books itself, I would imagine I could do something like this: 为了获得书籍本身的清单,我想我可以做这样的事情:
List<?> allBooks = JsonPath.<List<?>>read(context, "$.store.book");
Does it make sense to think about it this way? 这样考虑是否有意义?
It's the logic for iterating through this that I'm uncertain about. 这是我不确定的逻辑。
I would have thought I could define a "Book" pojo and then do something like this: 我本以为可以定义一个“ Book” pojo,然后执行以下操作:
for (int ctr = 0; ctr < allBooks.size(); ++ ctr) {
Book book = JsonPath.<Book>read(context, ".[" + ctr + "]");
System.out.println("book[" + book + "]");
}
However, this doesn't work. 但是,这不起作用。 The "
read
" method at this point returns a JSONArray
. 此时的“
read
”方法返回一个JSONArray
。
The last line in the code sample at https://github.com/jayway/JsonPath#what-is-returned-when is close to what I'm looking at, but this requires parsing the json in every iteration. 代码示例的最后一行位于https://github.com/jayway/JsonPath#what-is-returned-when与我正在查看的内容接近,但这需要在每次迭代中解析json。 It seems like the "
DocumentContext
" class has " read
" methods that can take a type parameter, but not " JsonPath
". 似乎“
DocumentContext
”类具有“ read
”方法,这些方法可以采用类型参数,而不能采用“ JsonPath
”。
What are some reasonable strategies for navigating something like this? 导航类似的东西有哪些合理的策略?
JSON path will just return you a list of Maps
as you've no doubt already seen. 毫无疑问,JSON路径只会返回一个
Maps
列表。 You need a way to tell it how to map these values to an object - for this you will need a custom configuration. 您需要一种方法来告诉它如何将这些值映射到对象-为此,您将需要自定义配置。 There are other providers like Gson etc., but I've only used Jackson.
还有其他提供商,例如Gson等,但我只用过Jackson。
Configuration configuration = Configuration
.builder()
.jsonProvider(new JacksonJsonProvider())
.mappingProvider(new JacksonMappingProvider())
.build();
The second step is to specify generic type information with a TypeRef
and pass it along when reading the tag. 第二步是使用
TypeRef
指定通用类型信息,并在读取标签时将其传递。
List<Book> allBooks = JsonPath.using(configuration)
.parse(context)
.read("$.store.book", new TypeRef<List<Book>>() {});
As a result you get a nice list of Book
objects. 结果,您得到一个不错的
Book
对象列表。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.