使用 Jackson 将 JSON 数组反序列化为具有私有列表 属性 的对象

Deserialize JSON Array to Object with private list property using Jackson

一个JSON字符串,如:

[
  "a", "b", "c"
]

通常会被反序列化为 List<String>。但是我有一个 class 看起来像这样:

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字符串反序列化为classFoo的对象,如:

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

这怎么可能?

我已经尝试将 @JsonCreator 与构造函数一起使用,但总是得到:

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

对于 Jackson 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]