2016-03-01 54 views
1

考慮這個代碼,我寫了傑克遜的多態序列化支持播放/反序列化(http://wiki.fasterxml.com/JacksonPolymorphicDeserialization) -類型標識字段沒有得到設置在序列化多態對象的名單

public class Main { 

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

    public static class Dog extends Animal { 
     public int barkLevel; 
    } 

    public static class Cat extends Animal { 
     public int meowLevel; 
    } 

    public static void main(String[] args) throws Exception { 

     String marshalled = "" + 
      "[\n" + 
      " {\n" + 
      "  \"name\"  : \"cookie\",\n" + 
      "  \"type\"  : \"dog\",\n" + 
      "  \"barkLevel\" : 5\n" + 
      " },\n" + 
      " {\n" + 
      "  \"name\"  : \"misty\",\n" + 
      "  \"type\"  : \"cat\",\n" + 
      "  \"meowLevel\" : 3\n" + 
      " }\n" + 
      "]\n"; 

     ObjectMapper mapper = new ObjectMapper(); 
     mapper.enable(SerializationFeature.INDENT_OUTPUT); 

     List<Animal> unmarshalledList = mapper.readValue(
      marshalled, 
      new TypeReference<List<Animal>>() {} 
     ); 

     Animal[] unmarshalledArray = mapper.readValue(
      marshalled, 
      new TypeReference<Animal[]>() {} 
     ); 

     for (Animal animal : unmarshalledList) { 
      System.out.println(animal.getClass().getSimpleName()); 
     } 
     System.out.println(
      mapper.writeValueAsString(
       unmarshalledList 
      ) + "\n" 
     ); 

     for (Animal animal : unmarshalledArray) { 
      System.out.println(animal.getClass().getSimpleName()); 
     } 
     System.out.println(
      mapper.writeValueAsString(
       unmarshalledArray 
      ) 
     ); 
    } 
} 

它產生下面的輸出 -

Dog 
Cat 
[ { 
    "name" : "cookie", 
    "barkLevel" : 5 
}, { 
    "name" : "misty", 
    "meowLevel" : 3 
} ] 

Dog 
Cat 
[ { 
    "type" : "dog", 
    "name" : "cookie", 
    "barkLevel" : 5 
}, { 
    "type" : "cat", 
    "name" : "misty", 
    "meowLevel" : 3 
} ] 

我的問題是 - 當我序列化列表<Animal>時,生成的json中不包含任何類型字段。但是,如果我使用Animal [],則生成的json中將包含類型字段。在這兩種情況下,反序列化都可以正常工作,即。使用正確的子類。有人能解釋這種行爲的原因嗎?

回答

1

要使用多態序列化序列化一個泛型集合,你需要做到以下幾點:

mapper.writerFor(new TypeReference<List<Animal>>() {}).writeValueAsString(unmarshalledList)); 

關於爲什麼這是必要的詳細信息,請參見this GitHub issue

相關問題