ObjectNode 对象读取列表值

ObjectNode object to read a list value

我有一个 JSON 回复是这样的:

{
  "id_list":["123", "456", "789"],
  ...
}

我想知道如果我想使用 ObjectNode 读取这样的 id 列表并 return 例如一个 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 reader 将其反序列化为 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());

然后将列表作为参数添加到函数中:

Set<String> resolvedId = bookIdResolver.fetchBookIds(bookIds);

很有魅力!