I have the case where I have some existing data which is present in multiple forms, but needs to be read into the same class.
For example, given the class:
@Getter
@NoArgsConstructor
@AllArgsConstructor
public class Item {
private UUID itemId;
}
I might have some JSON that is well-formed and is parseable out-of-the-box (e.g. List<Item>
):
{
"items": [
{
"itemId": "<uuid>"
}
]
}
but also some which is not:
{
"items": [
{
"someItemId": "<uuid>"
}
]
}
I do not have source JSON which contains both of these fields at the same time.
I tried to do this using a custom deserialization handler as described in this question, but my use case is a bit different since I will be essentially doing something like:
try {
Item item = defaultDeserializer.deserialize(...);
} catch (UnrecognizedPropertyException e) {
// try to rebuild object manually by traversing the tree
}
which would be rather difficult to get right since I can't let Jackson do the heavy lifting anymore. Are there alternative ways? Is there perhaps an annotation-based approach that would allow something like "source this field from either one of these JSON fields, but not both"?
You can use @JsonAlias
like this:
@Getter
@NoArgsConstructor
@AllArgsConstructor
public class Item {
@JsonAlias("someItemId")
private UUID itemId;
}