2015-04-07 98 views
0

JSON字符串如私人列表屬性對象。但我有一個類,看起來像這樣:反序列化JSON陣列來使用傑克遜

public class Foo { 
    private List<String> theList; 

    public Foo(List<String> theList) { 
     this.theList = theList; 
    } 

    public String toString() { 
     return new ObjectMapper().writeValueAsString(theList); 
    } 

    // ... more methods 
} 

現在我想上面的JSON字符串反序列化爲Foo類等的對象:

Foo foo = new ObjectMapper().readValue(jsonString, Foo.class); 

這怎麼可能?

我已經嘗試過使用@JsonCreator與構造函數,但總是得到:

JsonMappingException: Can not deserialize instance of ... out of START_ARRAY token 

回答

3

與傑克遜2.4.3,這

@JsonCreator 
public Foo(List<String> theList) { 
    this.theList = theList; 
} 
... 

String jsonString = "[\"a\", \"b\", \"c\"]"; 
Foo foo = new ObjectMapper().readValue(jsonString, Foo.class); 
System.out.println(foo.getTheList()); 

爲我工作。它打印

[a, b, c] 
+0

你是對的,我混淆了com.fasterxml.jackson和org.codehouse.jackson進口:-( – lathspell