我有一个JSON响应,像这样:
{
"id_list":["123", "456", "789"],
...
}
我想知道如果我想使用ObjectNode来读取这样一个id列表并返回一个id列表,我应该怎么做。
我试着这样做:
List<String> sendBookIds = asStream(objectMapper.readValue(on.get("bookIds"), new TypeReference<List<String>>(){}))
.map(JsonNode::asText)
.flatMap(bookIds -> idResolver.fetchBookIds(bookIds).stream())
.distinct()
.collect(Collectors.toList());
但是我有这个错误:
Cannot resolve method 'readValue(com.fasterxml.jackson.databind.JsonNode, anonymous com.fasterxml.jackson.core.type.TypeReference<java.util.List<java.lang.String>>
有谁知道是否有一个魔法丢失命令?如果不是,那么解决方案是什么?
您可以在JsonNode
节点中读取"id_list"
属性,然后使用自定义ObjectReader
读取器将其反序列化为List<String>
列表:
JsonNode node = mapper.readTree(json).get("id_list");
ObjectReader reader = mapper.readerFor(new TypeReference<List<String>>(){});
//the list will be ["123", "456", "789"]
List<String> idList = reader.readValue(node);
我找到了一个方法。首先,我从JsonNode收集id到字符串列表:
List<String> sendBookIds = asStream(on.get("bookIds"))
.map(JsonNode::asText)
.collect(Collectors.toList());
然后将list作为参数添加到函数中:
Set<String> resolvedId = bookIdResolver.fetchBookIds(bookIds);
工作像一个魅力!