'Json, Jackson: polymorphism of one field, based on the value of other field
Basically I'm trying to integrate with some other service that sends payloads with the following shape
{
"storeId":"123",
"type": "...",
"data": ...,
"createdAt": "...."
}
That shape never changes except for the property data, whose structure depends on the property type.
How can that be achieved with Jackson?
Solution 1:[1]
- Use
JsonNodeto convert from string to json nodesJsonNode node = mapper.valueToTree(fromValue); - Then get your node using
JsonNode dataNode = node.get("data"), same for type. - Get the class from the type node using
Class yourBeanClass = Class.forName("package.+type from step 2"); - Tokenize your data node using
JsonParser parser = mapper.treeAsTokens(dataNode); - Finally get your bean instance by doing
YourBean bean = mapper.readValue(parser, yourBeanClass);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Abe |
