我们使用Jersey/Jackson将JSON数据解组为java DTO.我的一个DTO是一个抽象类,我想将JSON数据解组到他的扩展DTO之一.例如,假设我有这些DTO:
public abstract class AnimalDTO{} public class DogDTO extends AnimalDTO{} public class CatDTO extends AnimalDTO{}
我想解组这个JSON数据:
{Zoo: {Animals:[{"type"="DogDTO", "code"="001", "name"="chihuahua"}, {"type"="CatDTO", "code"="002", "name"="felix"}]}}
因为"类型"会给出我想要解组的DTO类型.但似乎没有考虑这个属性.有没有我错过的,或误解了JSON语法?
谢谢.
在您的情况下,您应该使用@JsonTypeInfo
注释.
有关更多信息,请参阅以下链接:
JacksonFAQ.
Jackson 1.5:多态类型处理,第一步.
使用上面的链接,我创建了一个简单的示例,它使用类名序列化POJO对象:
import java.io.StringWriter; import java.util.Arrays; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.databind.ObjectMapper; public class JacksonProgram { public static void main(String[] args) throws Exception { DogDTO dog = new DogDTO(); dog.setCode("001"); dog.setName("chihuahua"); CatDTO cat = new CatDTO(); cat.setCode("002"); cat.setName("felix"); Zoo zoo = new Zoo(); zoo.setAnimals(new AnimalDTO[] { dog, cat }); Data data = new Data(); data.setZoo(zoo); ObjectMapper objectMapper = new ObjectMapper(); StringWriter writer = new StringWriter(); objectMapper.writeValue(writer, data); System.out.println(writer); } } @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type") abstract class AnimalDTO { private String code; private String name; public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { return "AnimalDTO [code=" + code + ", name=" + name + "]"; } } class DogDTO extends AnimalDTO { } class CatDTO extends AnimalDTO { } class Zoo { @JsonProperty(value = "Animals") private AnimalDTO[] animals; public AnimalDTO[] getAnimals() { return animals; } public void setAnimals(AnimalDTO[] animals) { this.animals = animals; } @Override public String toString() { return "Zoo [animals=" + Arrays.toString(animals) + "]"; } } class Data { @JsonProperty(value = "Zoo") private Zoo zoo; public Zoo getZoo() { return zoo; } public void setZoo(Zoo zoo) { this.zoo = zoo; } @Override public String toString() { return "Data [zoo=" + zoo + "]"; } }
该程序打印:
{"Zoo":{"Animals":[{"type":"DogDTO","code":"001","name":"chihuahua"},{"type":"CatDTO","code":"002","name":"felix"}]}}