Created
February 11, 2014 17:20
-
-
Save christophercurrie/8939489 to your computer and use it in GitHub Desktop.
Example of Polymorphic Deserialization using Jackson
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import com.fasterxml.jackson.annotation.JsonSubTypes; | |
import com.fasterxml.jackson.annotation.JsonTypeInfo; | |
import com.fasterxml.jackson.databind.PropertyNamingStrategy; | |
import com.fasterxml.jackson.databind.annotation.JsonNaming; | |
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type") | |
@JsonSubTypes({ | |
@JsonSubTypes.Type(value=AudioAttachment.class, name="audio"), | |
@JsonSubTypes.Type(value=LinkAttachment.class, name="link") | |
}) | |
public class Attachment { | |
} | |
@JsonNaming(PropertyNamingStrategy.LowerCaseWithUnderscoresStrategy.class) | |
public class Audio { | |
public int aid; | |
public int ownerId; | |
} | |
public class AudioAttachment extends Attachment { | |
public Audio audio; | |
} | |
public class Link { | |
public String url; | |
public String title; | |
} | |
public class LinkAttachment extends Attachment { | |
public Link link; | |
} | |
Could you please give an example of Custom Deserializer for Object Composition.
public class Parent{
String p_memeber1;
String p_memeber2;
CompClass1 comp1;
CompClass2 comp2;
...
..
}
public Class CompClass1{
String comp1_member1;
String comp1_member2;
SubCompClass1 subCom1;
...
...
}
public Class CompClass2{
String comp2_member1;
String comp2_member2;
SubCompClass2 subCom2;
...
...
}
I want the json String to be deserialize into a Parent Object with all the nested objects details populated as well.
Here is a good article describing how to deal with Polymorphism and Jackson Deserialization: https://octoperf.com/blog/2018/02/01/polymorphism-with-jackson/
Excellent tutorial!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi,
Thanks for this very clear example.
Do you know if this could work if the SubTypes are in different Maven projects ?
i.e: Audio, AudioAttachment and Link are each inside a different Maven project than Attachment.
I have a problem with circular dependency and can't figure a way out of it.
Thanks