I’m trying to use ObjectMapper to deserialize json but got some problem. Probably what I want is not possible with ObjectMapper but I will ask anyway for a good approach. Let’ say I have a class with the list of objects like this:
public class SomeClass {
ArrayList<BaseClass> list;
}
public class BaseClass {
String id;
String type;
}
public class MyClass1 extends BaseClass{
}
public class MyClass2 extends BaseClass{
}
And a json like this:
{
"list": [
{
"id": "1",
"type": "MyClass1",
},
{
"id": "2",
"type": "MyClass2",
},
{
"id": "3",
"type": "MyClass1",
}
]
}
The question is how to tell ObjectMapper to create and put to the list not a BaseClass
objects but MyClass1, MyClass2...
objects depends on the value of "type"? Is that possible?
3
Answers
You may try to create a customer Mapper, something like:
You can make this happen simply using Jackson annotations:
You may also want to look into other values for
use
, such asCLASS
orMINIMAL_CLASS
.See jackson polymorphic type handling annotations
You should be able to do something like