Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple Any-Setters using jackson?

Tags:

json

jackson

I have a dynamic field, where the key is unknown and the value can be either a String or an Object. Also, the field itself can be a map or just a single value. How can I instruct Jackson to serialize/deserialize this field according to it's value type? I'd also like to save my typed object to use in my code and not just use a map of Map<String, Object>.

public class MyPackage {

    @JsonProperty("versions")
    public Versions versions = new Versions();

    @JsonAnySetter
    public void add(String key, MyVersionObject value) {
        versions.put(key, value);
    }

    @JsonAnyGetter
    public Map<String, MyVersionObject> getMap() {
        return versions;
    }
}

Different JSONs that this field should accept:

{
    "versions": {
        "1.0": { ... MyVersionObject fields},
        "2.0": { ... MyVersionObject fields},
        "3.0": { ... MyVersionObject fields},
    }
}

Or

{
    "versions": {
        "3.0": "latest"
    }
}
like image 279
shayy Avatar asked Aug 05 '26 10:08

shayy


1 Answers

Sounds like input is so irregular that you can't really define this dynamically. So leave type of value as Object; this will give you String or Map. And from that, convert yourself; either manually, or by using ObjectMapper.convertValue() method.

like image 165
StaxMan Avatar answered Aug 07 '26 05:08

StaxMan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!