'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]

  1. Use JsonNode to convert from string to json nodes JsonNode node = mapper.valueToTree(fromValue);
  2. Then get your node using JsonNode dataNode = node.get("data"), same for type.
  3. Get the class from the type node using Class yourBeanClass = Class.forName("package.+type from step 2");
  4. Tokenize your data node using JsonParser parser = mapper.treeAsTokens(dataNode);
  5. 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