0

I have the following json:

[
    {
        "dog":{
            "noise":"bark",
            "dogfood":"something"
        }
    },
    {
        "cat":{
            "noise":"meow",
            "catfood":"iams"
        }
    }
]

and the following models:

public abstract class Animal {
}

public class Dog {
    private String noise;
    private String dogFood;
}

public class Cat {
    private String noise;
    private String catFood;
}

How do I deserialize each item in the json array with inheritance based on whether the root name for each element is dog or cat?

b15
  • 2,101
  • 3
  • 28
  • 46
  • 3
    Use a JSON parser. And `if` statements (or a `switch` statement). – Andreas Jul 22 '19 at 19:35
  • 1
    He/She already stated that wanted to use Jackson; read the question's title. – x80486 Jul 22 '19 at 19:37
  • 1
    @x80486 Ok, I'll shorten my comment: Use `if` statements or a `switch` statement. – Andreas Jul 22 '19 at 19:39
  • @Andreas you're saying there's no feature to handle this out of the box? If you want to give an example of using Jackson to query the root node name and switching based on the result that would be appreciated. – b15 Jul 22 '19 at 20:37

1 Answers1

1

At the Github page of Jackson someone asked for a solution for the the same problem as what you are facing, see here: https://github.com/FasterXML/jackson-databind/issues/1627

A work around for the time-being would be a custom deserializer where a field within the class should contain what type of class it is so it can be properly deserialized. See here for the work around: https://stackoverflow.com/a/50013090/6777695

Hakan54
  • 3,121
  • 1
  • 23
  • 37