问题
A JSON string like:
[
"a", "b", "c"
]
Would usually be deserialized to List<String>
. But I have a class that looks like this:
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
}
Now I want to deserialize the above JSON string into an object of class Foo
like:
Foo foo = new ObjectMapper().readValue(jsonString, Foo.class);
How is that possible?
I've already tried to use @JsonCreator
with the constructor but always get:
JsonMappingException: Can not deserialize instance of ... out of START_ARRAY token
回答1:
With Jackson 2.4.3, this
@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());
works for me. It prints
[a, b, c]
来源:https://stackoverflow.com/questions/29495261/deserialize-json-array-to-object-with-private-list-property-using-jackson