Deserialize JSON Array to Object with private list property using Jackson

↘锁芯ラ 提交于 2020-01-17 08:14:09

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!