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

Deserialize a JSON wrapped in an object with an unknown property name using Jackson

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

我 运行 遇到的问题是,一个特定的 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 */
    },
    ...
  ]
}

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

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

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

我认为最简单的解决方案是使用自定义 JsonDeserializer。它允许您逐步解析输入并仅提取构建对象所需的信息。

这是一个如何实现自定义解串器的简单示例:custom jackson deserializer

没有自定义反序列化器的最简单的解决方案是使用 @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;
}

要使用它,您只需执行以下操作:

new ObjectMapper().readValue(myJson, Wrapper.class);

相反,您可以使用 @JsonAnyGetter,在这种情况下应该 return 和 Map<String, List<Stuff>)