FasterXML / jackson-annotations

Core annotations (annotations that only depend on jackson-core) for Jackson data processor
https://github.com/FasterXML/jackson
Apache License 2.0
1.03k stars 330 forks source link

A problem when handling polymorphic types #168

Closed yanyouqiang1 closed 4 years ago

yanyouqiang1 commented 4 years ago
@Data
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "feetType",include = JsonTypeInfo.As.PROPERTY)
@JsonSubTypes({
        @JsonSubTypes.Type(name = "two", value = Animal.TwoFeetAnimal.class),
        @JsonSubTypes.Type(name = "four", value = Animal.FourFeetAnimal.class),
})
public abstract class Animal {
    String name;

    @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "landType",include = JsonTypeInfo.As.PROPERTY)
    @JsonSubTypes({
            @JsonSubTypes.Type(name = "land", value = FourFeetAnimal.LandAnimal.class),
            @JsonSubTypes.Type(name = "water", value = FourFeetAnimal.WaterAnimal.class),
    })
    @Data
    public static abstract class FourFeetAnimal extends Animal{
        int feet;

        @Data
        public static class LandAnimal extends FourFeetAnimal{
            String text1;
        }
        @Data
        public static class WaterAnimal  extends FourFeetAnimal{
            String text2;
        }

    }
    public static class TwoFeetAnimal extends Animal{

    }

}

Test

public class Test {
    public static void main(String[] args) throws JsonProcessingException {
        Animal.FourFeetAnimal.LandAnimal landAnimal = new Animal.FourFeetAnimal.LandAnimal();
        landAnimal.setText1("text1");
        landAnimal.setName("陆地动物");
        landAnimal.setFeet(4);

        ObjectMapper objectMapper = new ObjectMapper();
        final String string = objectMapper.writeValueAsString(landAnimal);
        System.out.println(string);
    }
}

result

{"landType":"land","name":"陆地动物","feet":4,"text1":"text1"}

The result ignores the feetType in Animal. An error is also reported when deserializing. In this case, what should I do?thanks all.

cowtowncoder commented 4 years ago

Issue tracker not meant for usage questions. Please use one of