【问题标题】:Deserialize JSON Array to Object with private list property using Jackson使用 Jackson 将 JSON 数组反序列化为具有私有列表属性的对象
【发布时间】:2015-04-07 15:25:55
【问题描述】:

一个 JSON 字符串,如:

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

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

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

【问题讨论】:

    标签: java json serialization jackson deserialization


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-03-02
      • 2023-03-13
      • 1970-01-01
      • 2020-07-27
      • 1970-01-01
      • 1970-01-01
      • 2021-05-03
      • 1970-01-01
      相关资源
      最近更新 更多