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"
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With