简体   繁体   English

使用带有嵌套类的Jackson JSON反序列化吗?

[英]Using Jackson JSON Deserialize with w/ nested class?

I'm new to using Jackson & deserializing JSON. 我是使用Jackson和反序列化JSON的新手。 I"m trying to create a message processor and have something like the following: 我正在尝试创建一个消息处理器,并具有以下内容:

@JsonDeserialize(builder = TestMessage.TestMessageBuilder.class)
private static class TestMessage {
    @Nonnull
    private Long timestamp;
    @Nonnull
    private String regionId;
    @Nonnull
    private String userId;
    @Nonnull
    private String action; 
    @Nonnull
    private TestMessageMetadata metadata;

    @JsonPOJOBuilder(withPrefix = "") 
    public static class TestMessageBuilder {}
}

The issue is that depending on what kind of action type the message comes in with, the TestMessageMetadata will need to be one of a set of a few different subclasses. 问题是,取决于消息附带的操作类型 ,TestMessageMetadata将需要是几个不同子类集合中的一个。 For example if action is "stream", TestMessageMetadata will need to be of type TestMessageStreamMetadata. 例如,如果操作为“ stream”,则TestMessageMetadata的类型将为TestMessageStreamMetadata。 Each subclass of TestMessageMetadata has different attributes within it (TestMessageStreamMetadata may have 4 fields that only apply to "stream" type messages, while for some other action there might only be 1 field that only applies to that type of action etc.) TestMessageMetadata的每个子类都具有不同的属性(TestMessageStreamMetadata可能具有4个字段,仅适用于“流”类型的消息,而对于某些其他操作,可能只有1个字段仅适用于该类型的操作,等等。)

The processor needs to only have this one overarching message class, so what are some ways to handle the multiple action types? 处理器只需要具有这一总体消息类,那么处理多种操作类型的方法有哪些? Help would be greatly appreciated! 帮助将不胜感激!

The issue is that depending on what kind of action type the message comes in with, the TestMessageMetadata will need to be one of a set of a few different subclasses. 问题是,取决于消息附带的操作类型,TestMessageMetadata将需要是几个不同子类集合中的一个。

Seems you are looking for @JsonTypeInfo . 似乎您在寻找@JsonTypeInfo @JsonTypeInfo is used to handle polymorphic types. @JsonTypeInfo用于处理多态类型。 It configure cases where actual type of a property value may be one of multiple sub types. 它配置了属性值的实际类型可能是多个子类型之一的情况。

Following is an example: 以下是一个示例:

class TestMessage {

    private String action; 

    @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.EXTERNAL_POPERTY, propery = "action")
    @JsonSubTypes({
        @JsonSubTypes.Type(value = TestMessageStreamMetadata.class, name = "stream"),
        @JsonSubTypes.Type(value = TestMessageFooMetadata.class, name = "foo")
    })
    private TestMessageMetadata metadata;

}

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

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