Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
394 views
in Technique[技术] by (71.8m points)

java - How can I prevent Jackson from serializing a polymorphic type's annotation property?

I have polymorphic types and deserializing from JSON to POJO works. I followed the documentation here, in fact. When serializing POJOs into JSON I'm getting an unwanted attribute, specifically the logical type name.

import static org.codehaus.jackson.annotate.JsonTypeInfo.*;

@JsonTypeInfo(use=Id.NAME, include=As.PROPERTY, property="type")
@JsonSubTypes({
    @JsonSubTypes.Type(value=Dog.class, name="dog"),
    @JsonSubTypes.Type(value=Cat.class, name="cat")
})    
public class Animal { ... }

public class Dog extends Animal { ... }
public class Cat extends Animal { ... }

When Jackson serializes into JSON it provides the type information which I don't want to expose.

{"type":"dog", ... }
{"type":"cat", ... }

Can I prevent this somehow? I only want to ignore type when deserializing.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

A simple solution would be to just move the @JsonTypeInfo and @JsonSubTypes configs to a MixIn, and then only register the MixIn for deserialization.

mapper.getDeserializationConfig().addMixInAnnotations(MyClass.class, MyMixIn.class)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...