jackson json 带有元素子节点列表的反序列化器

jackson json deserializer with subnode list of elements

我有一个扩展 StdDeserializer<MyObject>MyObject 的解串器。在其 deserialize(JsonParser p, DeserializationContext ctxt) 中,我想将我正在反序列化的节点的子节点转换为 pojo 列表。鉴于 json 喜欢

{
  "property1" : "value1",
  ...
  "subnode" : [
    {
      "snProperty1" : "value1",
      "snProperty2" : "value2",
      ...
      "snPropertyN" : "valueN"
    },
    { ... }, // other elements like the one above
    { ... }
 ],
  ...
}

和 pojos

class Subnode {
    private String snProperty1;
    private String snProperty2;
    ...
    private Stirng snPropertyN;
    // getters and setters
}

class MyObject {
    private String property1;
    ...
    private List<Subnode> subnodes;
    // getters and setters
}

我希望反序列化器处理所有 Subnode 对象,而无需自己迭代和使用 Subnode 设置器。类似于 TypeReferences 和 ObjectMapper.

是实例化一个 ObjectMapper 来执行上述操作的唯一方法吗?例如

objectMapper.convertValue(subnode, new TypeReference<List<Subnode>>() {});

我在不使用 ObjectMapper 的情况下通过使用解析器 (p) 编解码器解决了这个问题。

List<Subnode> subnodes = new ArrayList<>();
if (myObject.hasNonNull("subnodeList")) {
    ObjectCodec codec = p.getCodec();
    for (JsonNode subnode : myObject.get("subnodeList")) {
        subnodes.add(codec.treeToValue(subnode, Subnode.class));
    }
}
myObject.setSubnodes(subnodes);