杰克逊将额外的字段反序列化为地图 [英] Jackson deserialize extra fields as map

查看:129
本文介绍了杰克逊将额外的字段反序列化为地图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望将JSON对象中的任何未知字段反序列化为地图中的条目,该地图是pojo的成员。

I'm looking to deserialize any unknown fields in a JSON object as entries in a map which is a member of a pojo.

例如json

{
  "knownField" : 5,
  "unknownField1" : "926f7c2f-1ae2-426b-9f36-4ba042334b68",
  "unknownField2" : "ed51e59d-a551-4cdc-be69-7d337162b691"
}

和pojo

class myObject{
  int knownField;
  Map<String, UUID> unknownFields;
  // getters/setters whatever
}

有没有办法配置这与杰克逊?如果没有,是否有一种有效的方法来编写 StdDeserializer 来做(假设 unknownFields 中的值可以是更复杂但众所周知的一致类型)?

Is there a way to configure this with jackson? If not, is there an effective way to write a StdDeserializer to do it (assume the values in unknownFields can be a more complex but well known consistent type)?

推荐答案

有一个功能和注释完全符合这个目的。

There is a feature and an annotation exactly fitting this purpose.

我测试过,它可以像你的例子一样使用UUID:

I tested and it works with UUIDs like in your example:

class MyUUIDClass {
    public int knownField;

    Map<String, UUID> unknownFields = new HashMap<>();

    // Capture all other fields that Jackson do not match other members
    @JsonAnyGetter
    public Map<String, UUID> otherFields() {
        return unknownFields;
    }

    @JsonAnySetter
    public void setOtherField(String name, UUID value) {
        unknownFields.put(name, value);
    }
}

它会像这样工作:

    MyUUIDClass deserialized = objectMapper.readValue("{" +
            "\"knownField\": 1," +
            "\"foo\": \"9cfc64e0-9fed-492e-a7a1-ed2350debd95\"" +
            "}", MyUUIDClass.class);

更常见的类型如字符串工作:

Also more common types like Strings work:

class MyClass {
    public int knownField;

    Map<String, String> unknownFields = new HashMap<>();

    // Capture all other fields that Jackson do not match other members
    @JsonAnyGetter
    public Map<String, String> otherFields() {
        return unknownFields;
    }

    @JsonAnySetter
    public void setOtherField(String name, String value) {
        unknownFields.put(name, value);
    }
}

我在这篇博文中首先发现了这个功能)。

这篇关于杰克逊将额外的字段反序列化为地图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆