将空 Jackson 节点反序列化到集合时遇到问题

use*_*256 2 java json jackson objectmapper

当我没有价值时,我正在测试deserializing一个对象。我希望该对象等于.collectionJsonNodenull

这就是我正在尝试的:

public class ImmutableDiscoveredUrlDeserializer extends JsonDeserializer<ImmutableDiscoveredUrl> {
String parentUrl;
Double parentUrlSentiment;
Set<String> childUrls;
Boolean isParentVendorUrl;
Map<TagClassification, Set<String>> parentUrlArticleTags;

/*
 * (non-Javadoc)
 * @see com.fasterxml.jackson.databind.JsonDeserializer#deserialize(com.fasterxml.jackson.core.JsonParser, com.fasterxml.jackson.databind.DeserializationContext)
 */
@Override
public ImmutableDiscoveredUrl deserialize(JsonParser p, DeserializationContext ctx)
    throws IOException {

    JsonNode node = p.readValueAsTree();
    parentUrl = defaultIfNull(node.get("parentUrl").asText(), null);
    childUrls = defaultIfNull(parseChildUrls(node), emptySet());
    isParentVendorUrl = defaultIfNull(Boolean.valueOf(node.get("isParentVendorUrl").asText()), null);
    parentUrlArticleTags = defaultIfNull(parseArticleTags(node.get("parentUrlArticleTags")), emptyMap());

    return ImmutableDiscoveredUrl.discoveredUrl().parentUrl(parentUrl)
                .parentUrlSentiment(parentUrlSentiment).childUrls(childUrls)
            .isParentVendorUrl(isParentVendorUrl).parentUrlArticleTags(parentUrlArticleTags);
}

private Set<String> parseChildUrls(JsonNode node) throws IOException {
    ObjectMapper tagsMapper = new ObjectMapper();
    return tagsMapper.convertValue(node, new TypeReference<Set<String>>() {});
}

private Map<TagClassification, Set<String>> parseArticleTags(JsonNode node) throws IOException {
    ObjectMapper tagsMapper = new ObjectMapper();
    return tagsMapper.convertValue(node, new TypeReference<Set<String>>() {});
}
Run Code Online (Sandbox Code Playgroud)

但我收到一个MismatchedInputException,指出没有要映射的内容。我怎样才能ObjectMapper返回一个空值?

hzp*_*zpz 5

既然你已经有了一个,JsonNode你可以使用ObjectMapper#convertValue

@Test
public void converts_null_to_null() throws Exception {
    ObjectMapper mapper = new ObjectMapper();
    JsonNode jsonNode = mapper.readTree("{\"foo\":null}");
    JsonNode foo = jsonNode.get("foo");

    Set<String> result = mapper.convertValue(foo, new TypeReference<Set<String>>() {});

    assertNull(result);
}
Run Code Online (Sandbox Code Playgroud)

convertValue()请注意,如果您传递普通的Map. 对于您的情况,您需要自行删除defaultIfNull并检查null

if (node.get("parentUrlArticleTags") !== null) {
    parentUrlArticleTags = parseArticleTags(node.get("parentUrlArticleTags"));
}
Run Code Online (Sandbox Code Playgroud)