Is there a way in Jackson to map json array’s positions to different class properties?
For example if we have an api that returns person properties as array (0 is the id, 1 is the name,2 is the age, etc.) how to map this to an object that has properties id, name and age?
"person": [
1,
"Evgeni",
35
]
record Person(Long id, String name, Integer age)
Looking for something like:
@JsonProperty("<get the item at position 1>") String name
2
Answers
You can create a custom deserializer using the JsonDeserializer interface and map the contents of a JSON array to the corresponding properties by overriding the class
deserialize(JsonParser p, DeserializationContext ctxt)
.Create a custom deserializer:
Annotate the class with the custom deserializer:
Deserialize the JSON:
You may try to use JSON library Josson to transform the JSON array into object.
https://github.com/octomix/josson
POJO Person
Deserialize, Transform and Convert
Transformation expression:
map()
: Construct an object.#
denote the zero based array index.::
extract the field value to become the key name.?
denote the current node value.mergeObjects()
: Merge multiple objects into one object.Output