Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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, here is the JSON:

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

Here is the POJO:

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

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)?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
323 views
Welcome To Ask or Share your Answers For Others

1 Answer

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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...