【发布时间】:2017-08-04 14:06:35
【问题描述】:
当我的 JsonNode 没有价值时,我正在测试 deserializing 到 collection 对象。我希望对象等于null。
这就是我正在尝试的:
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>>() {});
}
但我收到了MismatchedInputException,表示没有要映射的内容。如何让ObjectMapper 返回 null?
【问题讨论】:
标签: java json jackson objectmapper