Deserialization with @JsonSubTypes for no value - missing property error
I've also encountered this issue, and could not find an elegant solution using the mechanisms provided by Jackson (custom BeanDeserializer
, BeanDeserializerModifier
, etc.).
It looks like a bug in the way external type IDs are handled. I worked around it by:
- deserializing the JSON tring to a
JsonNode
; - manually inserting a
null
node if the required property is not present; - mapping the
JsonNode
to my desired value type.
My code looks something like the following:
public <T> T decode(String json, Class<T> type) throws IOException {
JsonNode jsonNode = mapper.readTree(json);
if (jsonNode.isObject() && (jsonNode.get("payload") == null || jsonNode.get("payload").size() == 0)) {
ObjectNode objectNode = (ObjectNode) jsonNode;
objectNode.putNull("payload");
}
return mapper.treeToValue(jsonNode, type);
}
Missing property 'type' while De/Serialization of Map the contains mixed subtype - polymorphism
Instead of:mapper.writeValue(sw, animals);
usemapper.writerFor(new TypeReference<Map<String, ? extends Animal>>() {}).writeValue(sw, animals);
And instead of:mapper.readValue(animlasStr, new TypeReference<Map<String, Animal>>() {});
use:mapper.readValue(animlasStr, new TypeReference<Map<String, ? extends Animal>>() {});
with empty constructors in all the classes
How to use dynamic deserialization on a property using JsonSubTypes?
You need to use JsonTypeInfo.As.EXTERNAL_PROPERTY. From documentation:
Inclusion mechanism similar to
PROPERTY
, except that property is
included one-level higher in hierarchy, i.e. as sibling property at
same level as JSON Object to type. Note that this choice can only be
used for properties, not for types (classes). Trying to use it for
classes will result in inclusion strategy of basic PROPERTY instead.
See also:
- Jackson JsonTypeInfo.As.EXTERNAL_PROPERTY doesn't work as expected
Polymorphic deserialization Jackson issue
You can see this post I think you'll find what you want :
Jackson JSON Polymorphism
PS : be carreful, you sometime have "_type" and sometime "type".
Related Topics
Javax.Net.Ssl.Sslexception: Certificate Doesn't Match Any of the Subject Alternative Names
Pass and Get Json String to Spring Controller
How to Convert a Byte to Its Binary String Representation
How to Map an Auto Increment Field in Hibernate
How to Check If an Arraylist of Strings Contains Substrings of Another Arraylist of Strings
Default Value in Lombok. How to Init Default With Both Constructor and Builder
Jpa Repository Query - Java.Lang.Object; Cannot Be Cast to Model
Adding a Custom Http Header to a Spring Boot Ws Call (Wstemplate)
Creating Random Numbers With No Duplicates
Java H2 In-Memory Database Error: Table Not Found
Android - Running a Background Task Every 15 Minutes, Even When Application Is Not Running
Subscript and Superscript a String in Android
Spring Data JPA Problem With Updating Multiple Entities
Spring Boot @Enablescheduling Conditionally