使用 Jackson 反序列化包装在具有未知属性名称的对象中的 JSON

Nat*_*han 5 java json jackson json-deserialization

我正在使用 Jackson 将 JSON 从 ReST API 反序列化为使用 Jackson 的 Java 对象。

我遇到的问题是,一个特定的 ReST 响应返回包装在由数字标识符引用的对象中,如下所示:

{
  "1443": [
    /* these are the objects I actually care about */
    {
      "name": "V1",
      "count": 1999,
      "distinctCount": 1999
      /* other properties */
    },
    {
      "name": "V2",
      "count": 1999,
      "distinctCount": 42
      /* other properties */
    },
    ...
  ]
}
Run Code Online (Sandbox Code Playgroud)

到目前为止,我(可能是天真的)反序列化 JSON 的方法是创建镜像 POJO 并让 Jackson 简单而自动地映射所有字段,它做得很好。

问题是 ReST 响应 JSON 具有对我实际需要的 POJO 数组的动态数字引用。我无法创建镜像包装 POJO,因为属性名称本身既是动态的,又是非法的 Java 属性名称。

对于我可以调查的路线的任何和所有建议,我将不胜感激。

rve*_*rve 4

无需自定义反序列化器的最简单解决方案是使用@JsonAnySetter. Jackson 将为每个未映射的属性调用带有此注释的方法。

例如:

public class Wrapper {
  public List<Stuff> stuff;

  // this will get called for every key in the root object
  @JsonAnySetter
  public void set(String code, List<Stuff> stuff) {
    // code is "1443", stuff is the list with stuff
    this.stuff = stuff;
  }
}

// simple stuff class with everything public for demonstration only
public class Stuff {
  public String name;
  public int count;
  public int distinctCount;
}
Run Code Online (Sandbox Code Playgroud)

要使用它,你可以这样做:

new ObjectMapper().readValue(myJson, Wrapper.class);
Run Code Online (Sandbox Code Playgroud)

相反,您可以使用@JsonAnyGetterwhichMap<String, List<Stuff>)在这种情况下应返回 a 。