繁体   English   中英

杰克逊基于对象属性反序列化为POJO

[英]Jackson Deserialize to POJO Based On Object Properties

是否可以使用Jackson将JSON反序列化为基于JSON内容的两种类型之一?

例如,我有以下Java(技术上是Groovy,但这并不重要)接口和类:

interface Id {
    Thing toThing() 
}

class NaturalId implements Id {

    final String packageId

    final String thingId

    Thing toThing() {
        new PackageIdentifiedThing(packageId, thingId)
    }         
}

class AlternateId implements Id {

    final String key

    Thing toThing() {
        new AlternatelyIdentifiedThing(key)
    }
}

我将收到的JSON将如下所示:

这个JSON应该映射到NaturalId {"packageId": "SomePackage", "thingId": "SomeEntity"}

此JSON应映射到AlternateId {"key": "SomeUniqueKey"}

有没有人知道我怎么能用Jackson 2.x完成这个,而不包括类型id?

这些是实现Id的唯一两个类吗? 如果是这样,您可以编写IdDeserializer类并在Id接口上放置@JsonDeserialize(using = IdDeserializer.class) ,反序列化器将查看JSON并确定要反序列化的对象。

编辑:JsonParser是流媒体所以它应该看起来像这样:

public Id deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {
    ObjectNode node = jp.readValueAsTree();
    Class<? extends Id> concreteType = determineConcreteType(node); //Implement 
    return jp.getCodec().treeToValue(node, concreteType);
}

使用@JsonIgnore注释您的方法

@JsonIgnore
Thing toThing() {
    new PackageIdentifiedThing(packageId, thingId)
}  

使用Jackson2,您可以使用泛型轻松编组到不同的类:

private <T> T json2Object(String jsonString, String type, Class<T> clazz) {
    JsonNode jsonObjectNode = getChildNode(jsonString, type);       
    T typeObject = null;
    try {
        typeObject = jacksonMapper.treeToValue(jsonObjectNode, clazz);
    } catch (JsonProcessingException jsonProcessingException) {
        LOGGER.severe(jsonProcessingException);
    }
    return typeObject;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM