dinup24
dinup24

Reputation: 1772

Jackson serialization using JsonTypeInfo WRAPPER_OBJECT

I am trying to set subclass name as the XML element name in the serialized XML content using Jackson in the following manner.

public interface Animal {
    public String getName();
}

public class Dog implements Animal {
    private String name;
    public String getName(){
        return name;
    }
}

public class Cat implements Animal {
    private String name;
    public String getName(){
        return name;
    }
}

public class Zoo {
    @JacksonXmlElementWrapper(useWrapping = false)
    @JsonTypeInfo(include = As.WRAPPER_OBJECT, use = Id.NAME)
    private List<Animal> animals;
    // getters and setters
}

Result:

<Zoo>
    <animals>
        <Dog>
            <name>xyz</name>
        </Dog>
    </animals>
    <animals>
        <Cat>
            <name>abc</name>
        </Cat>
    </animals>
</Zoo>

By adding @JsonTypeInfo(include = As.WRAPPER_OBJECT, use = Id.NAME), I am able to set class name as the wrapper object. Is it possible to eliminate <animal/> wrapper and generate the XML in the below format:

<Zoo>
    <Dog>
        <name>xyz</name>
    </Dog>
    <Cat>
        <name>abc</name>
    </Cat>
</Zoo>

Upvotes: 2

Views: 2410

Answers (1)

dinup24
dinup24

Reputation: 1772

I was able find out an answer myself. We can achieve this using a custom serializer as illustrated below.

public class Zoo {
    @JacksonXmlElementWrapper(useWrapping = false)
    @JsonSerialize(using=AnimalListSerializer.class)
    private List<Animal> animals;
    // getters and setters
}

public class AnimalListSerializer extends JsonSerializer<List<Animal>> {
    @Override
    public void serialize(List<Animal> value, JsonGenerator jgen,
            SerializerProvider provider) throws IOException,
            JsonProcessingException {

        for (Animal me : value) {
            provider.defaultSerializeField(me.getClass().getName(), me,
                    jgen);
        }
    }
}

Upvotes: 2

Related Questions