问题
I try to have Jackson property type info serialized, even when my type is referenced by a map.
With this simple sample:
import java.util.HashMap;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.JsonTypeName;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class DemoJackson {
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY)
public static abstract class Animal {}
@JsonTypeName("cat")
public static class Cat extends Animal {}
public static void main(String[] args) throws JsonProcessingException {
ObjectMapper objectMapper = new ObjectMapper();
Cat cat = new Cat();
System.out.println(objectMapper.writeValueAsString(cat));
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("data", cat);
System.out.println(objectMapper.writeValueAsString(map));
}
}
I get:
{"@type":"cat"}
{"data":{}}
But I would like to have:
{"@type":"cat"}
{"data":{"@type":"cat"}}
Is it possible? How to do it?
I have tried with enableDefaultTyping
but I get:
{"@type":"cat"}
{"data":["DemoJackson$Cat",{}]}
回答1:
When you are serializing a map directly, as you do, the object mapper needs the type information about the map contents because of generic typing. Please refer to chapter 5.1 of Polymorphic Type Handling wiki page.
An example of passing the type reference information when serializing the map of Animals.
objectMapper.writerWithType(new TypeReference<Map<String, Animal>>() {})
.writeValueAsString(map)
Output:
{"@type":"cat"}
{"data":{"@type":"cat"}}
来源:https://stackoverflow.com/questions/23172718/how-to-make-polymorphic-jackson-serialization-working-with-map