简体   繁体   English

在Jackson中反序列化同名但不同类型的属性?

[英]Deserializing attributes of same name but different types in Jackson?

I have a REST API which returns a JSON response as: 我有一个REST API,它返回一个JSON响应:

{
    "channel" : "JHBHS"
}

and sometimes it returns: 有时会返回:

{
    "channel": {
                    "id": 12321,
                    "name": "Some channel"
               }
}

I have a POJO like: 我有一个像POJO:

public class Event {
    private String channel;
    @JsonProperty("channel")
    private Channel channelObj;
}

public class Channel {
    private int id;
    private String name;
}

So, is there a way (other than writing your own custom deserializer ) in Jackson2 which will help me map channel in JSON to String type when it's a String and Channel type when it's a JSON Object? 那么,在Jackson2中是否有一种方法(除了编写自己的自定义反序列化器 ),这将帮助我将JSON中的channel映射到String类型,当它是一个JSON对象时是StringChannel类型?

Or in other words, is there a way in Jackson which maps by type of the variable and not just by name ? 或者换句话说,杰克逊有没有一种方法可以按变量的type而不是按name进行映射?

I can suggest you to use JsonNode like this: 我建议你像这样使用JsonNode

class Event {

    @JsonProperty("channel")
    private JsonNode channelInternal;

    private Channel channel;

    private String channelStr;

    /**
     * Custom getter with channel parsing
     * @return channel
     */
    public Channel getChannel() {
        if (channel == null && channelInternal != null) {
            if (channelInternal.isObject()) {
                int id = channelInternal.get("id").intValue();
                String name = channelInternal.get("name").asText();
                channel = new Channel(id, name);
            }
        }
        return channel;
    }

    /**
     * Custom getter with channel string parsing
     * @return channel string
     */
    public String getChannelStr() {
        if (channelStr == null && channelInternal != null) {
            if (channelInternal.isTextual()) {
                channelStr = channelInternal.asText();
            }
        }
        return channelStr;
    }
}

or like this : 或者像这样

class Event {

    private Channel channel;

    private String channelStr;

    @JsonSetter("channel")
    public void setChannelInternal(JsonNode channelInternal) {
        if (channelInternal != null) {
            if (channelInternal.isTextual()) {
                channelStr = channelInternal.asText();
            } else if (channelInternal.isObject()) {
                int id = channelInternal.get("id").intValue();
                String name = channelInternal.get("name").asText();
                channel = new Channel(id, name);
            }
        }
    }

    public Channel getChannel() {
        return channel;
    }

    public String getChannelStr() {
        return channelStr;
    }
}

But I think using custom deserializer is more common. 但我认为使用自定义解串器更常见。

Here is test code 这是测试代码

public static void main(String[] args) throws IOException {
    ObjectMapper objectMapper = new ObjectMapper();
    String source1 = "{\n" +
            "    \"channel\" : \"JHBHS\"\n" +
            "}";
    String source2 = "{\n" +
            "    \"channel\": {\n" +
            "                    \"id\": 12321,\n" +
            "                    \"name\": \"Some channel\"\n" +
            "               }\n" +
            "}";

    //Test object parsing
    Event result = objectMapper.readValue(source2, Event.class);
    System.out.println(String.format("%s : %s", result.getChannel().getId(), result.getChannel().getName()));

    //Test string parsing
    result = objectMapper.readValue(source1, Event.class);
    System.out.println(result.getChannelStr());
}

And the output: 并输出:

12321 : Some channel
JHBHS

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

相关问题 简单XML反序列化具有相同名称的不同元素类型 - Simple XML deserializing different element types with the same name Java Jackson对具有相同名称但不同类类型的对象进行反序列化 - Java Jackson deserialize objects of the same name but different class types Json 与 POJO + Jackson 具有相同名称和不同类型的任何字段的模式 - Json schema with anyOf field with same name and different types to POJO + Jackson 杰克逊反序列化有界类型 - Jackson deserializing bounded types 使用jackson从改造中反序列化json,其中相同的变量名称可以表示两个不同的对象 - Deserializing json from retrofit using jackson where same variable name can represent two different objects 使用Jackson进行序列化和反序列化时,处理某些字段的不同类型 - Handle different types for some fields while serializing and deserializing with Jackson 杰克逊-反序列化为其他类型 - Jackson - Deserializing to a Different Type 使用SimpleFramework反序列化多个不同的标签(具有相同的名称) - Deserializing multiple different tags (with the same name) with SimpleFramework 使用 Jackson 使用 @JsonUnwrapped 反序列化多态类型 - Deserializing Polymorphic Types with @JsonUnwrapped using Jackson Jackson 反序列化 - 错误的主体类型成功反序列化 - Jackson Deserialization - Wrong body types sucessfully deserializing
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM