Jackson deserialize extra fields as map

后端 未结 1 863
悲&欢浪女
悲&欢浪女 2020-12-09 09:17

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

For example the json

{
  \"knownFiel         


        
相关标签:
1条回答
  • 2020-12-09 09:32

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

    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);
        }
    }
    

    And it would work like this:

        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);
        }
    }
    

    (I found this feature in this blog post first).

    0 讨论(0)
提交回复
热议问题