I need to deserialize JSON looks like the following:
{
"data": [{
"id": "id1",
"type": "type1"
"name": "John",
...
},
{
"id": "id2",
"type": "type2",
"name": "Rebecca",
...
},
{
"id": "id3",
"type": "unknown",
"name": "Peter",
...
}]
}
For deserializing JSON which I have written above I have created a couple of classes:
@JsonTypeInfo(
use = JsonTypeInfo.Id.NAME,
property = "type",
defaultImpl = DefaultData.class
)
@JsonSubTypes({
@JsonSubTypes.Type(value = Type1Data.class, name = "type1"),
@JsonSubTypes.Type(value = Type2Data.class, name = "type2")
})
public class AbstractData {
public final String id;
public final String type;
public final String name;
public AbstractData(String id, String type, String name) {
this.id = id;
this.type = type;
this.name = name;
}
}
public class Type1Data extends AbstractData {
@JsonCreator
public Type1Data(@JsonProperty("id") String id,
@JsonProperty("name") String name
) {
super(id, "type1", name);
}
}
public class DefaultData extends AbstractData {
@JsonCreator
public DefaultData(@JsonProperty("id") String id,
@JsonProperty("type") String type,
@JsonProperty("name") String name
) {
super(id, type, name);
}
}
public class Main {
public static void main(String... args) {
ObjectMapper mapper = new ObjectMapper();
AbstractData data = mapper.readValue(json, AbstractData.class);
}
}
I get an exception if I use default implementation:
com.fasterxml.jackson.databind.exc.InvalidTypeIdException: Could not resolve type id 'unknown' as a type
The class DefaultData
I need to avoid a deserialization exception if I will get the unknown type.
How can I fix this issue?