简体   繁体   中英

Using Jackson JSON Deserialize with w/ nested class?

I'm new to using Jackson & deserializing 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. For example if action is "stream", TestMessageMetadata will need to be of type 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.)

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.

Seems you are looking for @JsonTypeInfo . @JsonTypeInfo is used to handle polymorphic types. 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;

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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