2015-01-01 31 views
4

我有一類設置與代表團傑克遜JSON力反序列化對象

public class MyClass implements List<Integer> { 

    public String name; 

    public List<Integer> target; // this is the delegation target 
    // more fields 

    @Override 
    public Integer get(int index) { 
     return target.get(index); 
    } 
    // all other method in target interface is delegated 
} 

而且我得到了一個JSON看起來像這樣:

{"target": [1, 2, 3] , "name":"foo"} 

和傑克遜拋出這個:

Exception in thread "main" com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of com.foo.MyClass out of START_OBJECT token 
at [Source: [email protected]; line: 1, column: 1] 
    at com.fasterxml.jackson.databind.JsonMappingException.from(JsonMappingException.java:164) 
    at com.fasterxml.jackson.databind.DeserializationContext.mappingException(DeserializationContext.java:691) 
    at com.fasterxml.jackson.databind.DeserializationContext.mappingException(DeserializationContext.java:685) 
    at com.fasterxml.jackson.databind.deser.std.CollectionDeserializer.handleNonArray(CollectionDeserializer.java:256) 
    at com.fasterxml.jackson.databind.deser.std.CollectionDeserializer.deserialize(CollectionDeserializer.java:214) 
    at com.fasterxml.jackson.databind.deser.std.CollectionDeserializer.deserialize(CollectionDeserializer.java:204) 
    at com.fasterxml.jackson.databind.deser.std.CollectionDeserializer.deserialize(CollectionDeserializer.java:23) 
    at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:2986) 
    at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2091) 

我在猜測傑克遜認爲MyClass是一個列表,所以不知道該怎麼辦{}因爲[]預計

我證實了通過使MyClass我的猜測沒有實現List<Integer>

public class MyClass { /*same stuff*/} 

和一切工作。但我需要MyClass來實現List<Integer> ....

模塊中是否有註釋或配置可用於解決此問題?

回答

2

我偶然發現了我的答案,而讀this article, 基本上,我需要我的註釋類

@JsonFormat(shape = Shape.OBJECT) 
1

你也許可以編寫一個自定義的反序列化器,但是我真的認爲如果你刪除List繼承,問題會好得多解決。

實現該接口的要求是什麼?對於頂層類來說,如果有一個訪問者來訪問列表而不是實現一個接口,會不會更有意義?從面向對象的角度來看,你的頂級課程不是一種「種類」的課程。刪除繼承,你有一個更清潔的設計,與傑克遜合作。

+0

嘛,'MyObject'是從庫,我不能改變:( – tom91136

+0

如果你絕對真真正必須使用''MyObject'',然後想到的選項是1)將自己的''JsonDeserializer''添加到''ObjectMapper'',或者2)從''MyObject''繼承並添加''JsonDeserializer'' '指定不同的解串器。我仍然認爲''MyObject''的繼承被破壞了。 –