1

Let say I've got an Item interface with three implementations (can be an abstract class as well if this would help).

interface Item {

    String getId();

    // ...
}

class TextItem implement Item {

    TextItem(String id, String text) {
        // ...
    }

    // ...
}

class NumberItem implement Item {

    NumberItem(String id, Integer number) {
        // ...
    }

    // ...
}

class FlagItem implement Item {

    FlagItem(String id, Boolean flag) {
        // ...
    }

    // ...
}

Is it possible to setup Jackson so it would create an instance of appropriate implementation based on the existence of property relevant for given item type?

Please see the below JSON example, each item has a different second property: text, number or flag. Each of these properties stores a different data type in it as well.

How could I deserialize without changing the JSON structure and ideally without writing a custom if-else based deserializer either?

{
    "items": [
        {
            "id": "item-1",
            "text": "some text"
        },
        {
            "id": "item-2",
            "number": 12345
        },
        {
            "id": "item-3",,
            "flag": true
        }
    ]
}

Data types chosen for the second item property are just an example. They could be some custom type or collection as well. The point is how to setup Jackson so it uses appropriate item implementation either by constructor argument types or by existence of property name specific for a given item type.

topr
  • 4,482
  • 3
  • 28
  • 35
  • If this is not possible with the current JSON structure, would it be if the second property shared the same name in JSON just kept a different value type? – topr Jun 27 '17 at 16:12
  • 1
    [This](https://stackoverflow.com/a/12459070/823393) may help. I needed something like this some time ago and cracked the problem. – OldCurmudgeon Jun 27 '17 at 16:21

0 Answers0