Deserialize JSON with Jackson with complex Polymorphic structure - java

I need help, here is the description of the task:
1. I have base interface
interface IPolymorphicModel
2. I have few nested interfaces:
interface IContentItem extends IPolymorphicModel
interface IAttachment extends IPolymorphicModel
3. I have few implementations:
public class MediaAttachment implements IAttachment
public class Article implements IContentItem {
private List<IAttachment> attachements;
}
I am using jackson (also I tried Gson using registerTypeAdapterFactory) to parse current json structure. I am using next approach for deserializing json using single Deserializer for all nested items:
Module module = new SimpleModule()
module.setDeserializerModifier(new BeanDeserializerModifier() {
public JsonDeserializer<?> modifyDeserializer(DeserializationConfig config,
BeanDescription beanDesc,
JsonDeserializer<?> deserializer){
if (IPolymorphicModel.class.isAssignableFrom(beanDesc.getBeanClass())){
return new PolymorphicJsonDeserializer()
}
return super.modifyDeserializer(config, beanDesc, deserializer);
})
But there is the problem with parsing inner items: as you can see inner object can contain object with the same super, and when jackson try to parse them it doesn't know anything about IPolymorphicModel and registering the same BeanDeserializerModifier is not possible because it will cause stack overflow.

I found the solution. And its quite easy at least in this case. To solve such kind of task, you need to use jackson TypeIdResolver. Here is an example:
1. First you need to annotate your base class, where modelType your field by which you can identify, which exactly child of base class you are using:
#JsonTypeInfo(use = JsonTypeInfo.Id.CUSTOM,
include = JsonTypeInfo.As.PROPERTY,
property = "modelType")
#JsonTypeIdResolver(IdResolver.class)
interface IPolymorphic
2. Implement your own IdResolver.class:
public class IdResolver implements TypeIdResolver {
private JavaType baseType = null;
#Override
public void init(JavaType baseType) {
this.baseType = baseType;
}
#Override
public String idFromValue(Object value) {
return idFromValueAndType(value, value.getClass());
}
#Override
public String idFromValueAndType(Object value, Class<?> suggestedType) {
String id = "";
for (Map.Entry<String, Class<? extends IPolymorphic>> entry : PolymorphicTypeRegistry.Companion.getInstance().getMap().entrySet()) {
if (entry.getValue() == suggestedType) return entry.getKey();
}
return id;
}
#Override
public String idFromBaseType() {
return idFromValueAndType(null, baseType.getRawClass());
}
#Override
public JavaType typeFromId(String id) {
Class clazz = PolymorphicTypeRegistry.Companion.getInstance().get(id);
JavaType javaType = TypeFactory.defaultInstance().constructSpecializedType(baseType, clazz);
return javaType;
}
#Override
public JavaType typeFromId(DatabindContext context, String id) {
return typeFromId(id);
}
#Override
public String getDescForKnownTypeIds() {
return "";
}
#Override
public JsonTypeInfo.Id getMechanism() {
return JsonTypeInfo.Id.CUSTOM;
}
}
In two previous steps we configure jackson to call the same deserialize behaviour for all nested classes of IPolymorphic, so the last step - we need to register deserializer for IPolymorphic:
public void configureJackson() {
ObjectMapper objectMapper = new ObjectMapper();
Module module = new SimpleModule();
module.addDeserializer(IPolymorphic.class, new PolymorphicJsonDeserializer());
objectMapper.registerModule(module);
}

Related

How to deserialize JSON to enum in Java? [duplicate]

How can I deserialize JSON string that contains enum values that are case insensitive? (using Jackson Databind)
The JSON string:
[{"url": "foo", "type": "json"}]
and my Java POJO:
public static class Endpoint {
public enum DataType {
JSON, HTML
}
public String url;
public DataType type;
public Endpoint() {
}
}
in this case,deserializing the JSON with "type":"json" would fail where as "type":"JSON" would work.
But I want "json" to work as well for naming convention reasons.
Serializing the POJO also results in upper case "type":"JSON"
I thought of using #JsonCreator and #JsonGetter:
#JsonCreator
private Endpoint(#JsonProperty("name") String url, #JsonProperty("type") String type) {
this.url = url;
this.type = DataType.valueOf(type.toUpperCase());
}
//....
#JsonGetter
private String getType() {
return type.name().toLowerCase();
}
And it worked. But I was wondering whether there's a better solutuon because this looks like a hack to me.
I can also write a custom deserializer but I got many different POJOs that use enums and it would be hard to maintain.
Can anyone suggest a better way to serialize and deserialize enums with proper naming convention?
I don't want my enums in java to be lowercase!
Here is some test code that I used:
String data = "[{\"url\":\"foo\", \"type\":\"json\"}]";
Endpoint[] arr = new ObjectMapper().readValue(data, Endpoint[].class);
System.out.println("POJO[]->" + Arrays.toString(arr));
System.out.println("JSON ->" + new ObjectMapper().writeValueAsString(arr));
Jackson 2.9
This is now very simple, using jackson-databind 2.9.0 and above
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.enable(MapperFeature.ACCEPT_CASE_INSENSITIVE_ENUMS);
// objectMapper now deserializes enums in a case-insensitive manner
Full example with tests
import com.fasterxml.jackson.databind.MapperFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
public class Main {
private enum TestEnum { ONE }
private static class TestObject { public TestEnum testEnum; }
public static void main (String[] args) {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.enable(MapperFeature.ACCEPT_CASE_INSENSITIVE_ENUMS);
try {
TestObject uppercase =
objectMapper.readValue("{ \"testEnum\": \"ONE\" }", TestObject.class);
TestObject lowercase =
objectMapper.readValue("{ \"testEnum\": \"one\" }", TestObject.class);
TestObject mixedcase =
objectMapper.readValue("{ \"testEnum\": \"oNe\" }", TestObject.class);
if (uppercase.testEnum != TestEnum.ONE) throw new Exception("cannot deserialize uppercase value");
if (lowercase.testEnum != TestEnum.ONE) throw new Exception("cannot deserialize lowercase value");
if (mixedcase.testEnum != TestEnum.ONE) throw new Exception("cannot deserialize mixedcase value");
System.out.println("Success: all deserializations worked");
} catch (Exception e) {
e.printStackTrace();
}
}
}
I ran into this same issue in my project, we decided to build our enums with a string key and use #JsonValue and a static constructor for serialization and deserialization respectively.
public enum DataType {
JSON("json"),
HTML("html");
private String key;
DataType(String key) {
this.key = key;
}
#JsonCreator
public static DataType fromString(String key) {
return key == null
? null
: DataType.valueOf(key.toUpperCase());
}
#JsonValue
public String getKey() {
return key;
}
}
Since Jackson 2.6, you can simply do this:
public enum DataType {
#JsonProperty("json")
JSON,
#JsonProperty("html")
HTML
}
For a full example, see this gist.
In version 2.4.0 you can register a custom serializer for all the Enum types (link to the github issue). Also you can replace the standard Enum deserializer on your own that will be aware about the Enum type. Here is an example:
public class JacksonEnum {
public static enum DataType {
JSON, HTML
}
public static void main(String[] args) throws IOException {
List<DataType> types = Arrays.asList(JSON, HTML);
ObjectMapper mapper = new ObjectMapper();
SimpleModule module = new SimpleModule();
module.setDeserializerModifier(new BeanDeserializerModifier() {
#Override
public JsonDeserializer<Enum> modifyEnumDeserializer(DeserializationConfig config,
final JavaType type,
BeanDescription beanDesc,
final JsonDeserializer<?> deserializer) {
return new JsonDeserializer<Enum>() {
#Override
public Enum deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {
Class<? extends Enum> rawClass = (Class<Enum<?>>) type.getRawClass();
return Enum.valueOf(rawClass, jp.getValueAsString().toUpperCase());
}
};
}
});
module.addSerializer(Enum.class, new StdSerializer<Enum>(Enum.class) {
#Override
public void serialize(Enum value, JsonGenerator jgen, SerializerProvider provider) throws IOException {
jgen.writeString(value.name().toLowerCase());
}
});
mapper.registerModule(module);
String json = mapper.writeValueAsString(types);
System.out.println(json);
List<DataType> types2 = mapper.readValue(json, new TypeReference<List<DataType>>() {});
System.out.println(types2);
}
}
Output:
["json","html"]
[JSON, HTML]
If you're using Spring Boot 2.1.x with Jackson 2.9 you can simply use this application property:
spring.jackson.mapper.accept-case-insensitive-enums=true
I went for the solution of Sam B. but a simpler variant.
public enum Type {
PIZZA, APPLE, PEAR, SOUP;
#JsonCreator
public static Type fromString(String key) {
for(Type type : Type.values()) {
if(type.name().equalsIgnoreCase(key)) {
return type;
}
}
return null;
}
}
For those who tries to deserialize Enum ignoring case in GET parameters, enabling ACCEPT_CASE_INSENSITIVE_ENUMS will not do any good. It won't help because this option only works for body deserialization. Instead try this:
public class StringToEnumConverter implements Converter<String, Modes> {
#Override
public Modes convert(String from) {
return Modes.valueOf(from.toUpperCase());
}
}
and then
#Configuration
public class WebConfig implements WebMvcConfigurer {
#Override
public void addFormatters(FormatterRegistry registry) {
registry.addConverter(new StringToEnumConverter());
}
}
The answer and code samples are from here
To allow case insensitive deserialization of enums in jackson, simply add the below property to the application.properties file of your spring boot project.
spring.jackson.mapper.accept-case-insensitive-enums=true
If you have the yaml version of properties file, add below property to your application.yml file.
spring:
jackson:
mapper:
accept-case-insensitive-enums: true
With apologies to #Konstantin Zyubin, his answer was close to what I needed - but I didn't understand it, so here's how I think it should go:
If you want to deserialize one enum type as case insensitive - i.e. you don't want to, or can't, modify the behavior of the entire application, you can create a custom deserializer just for one type - by sub-classing StdConverter and force Jackson to use it only on the relevant fields using the JsonDeserialize annotation.
Example:
public class ColorHolder {
public enum Color {
RED, GREEN, BLUE
}
public static final class ColorParser extends StdConverter<String, Color> {
#Override
public Color convert(String value) {
return Arrays.stream(Color.values())
.filter(e -> e.getName().equalsIgnoreCase(value.trim()))
.findFirst()
.orElseThrow(() -> new IllegalArgumentException("Invalid value '" + value + "'"));
}
}
#JsonDeserialize(converter = ColorParser.class)
Color color;
}
Problem is releated to com.fasterxml.jackson.databind.util.EnumResolver. it uses HashMap to hold enum values and HashMap doesn't support case insensitive keys.
in answers above, all chars should be uppercase or lowercase. but I fixed all (in)sensitive problems for enums with that:
https://gist.github.com/bhdrk/02307ba8066d26fa1537
CustomDeserializers.java
import com.fasterxml.jackson.databind.BeanDescription;
import com.fasterxml.jackson.databind.DeserializationConfig;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.deser.std.EnumDeserializer;
import com.fasterxml.jackson.databind.module.SimpleDeserializers;
import com.fasterxml.jackson.databind.util.EnumResolver;
import java.util.HashMap;
import java.util.Map;
public class CustomDeserializers extends SimpleDeserializers {
#Override
#SuppressWarnings("unchecked")
public JsonDeserializer<?> findEnumDeserializer(Class<?> type, DeserializationConfig config, BeanDescription beanDesc) throws JsonMappingException {
return createDeserializer((Class<Enum>) type);
}
private <T extends Enum<T>> JsonDeserializer<?> createDeserializer(Class<T> enumCls) {
T[] enumValues = enumCls.getEnumConstants();
HashMap<String, T> map = createEnumValuesMap(enumValues);
return new EnumDeserializer(new EnumCaseInsensitiveResolver<T>(enumCls, enumValues, map));
}
private <T extends Enum<T>> HashMap<String, T> createEnumValuesMap(T[] enumValues) {
HashMap<String, T> map = new HashMap<String, T>();
// from last to first, so that in case of duplicate values, first wins
for (int i = enumValues.length; --i >= 0; ) {
T e = enumValues[i];
map.put(e.toString(), e);
}
return map;
}
public static class EnumCaseInsensitiveResolver<T extends Enum<T>> extends EnumResolver<T> {
protected EnumCaseInsensitiveResolver(Class<T> enumClass, T[] enums, HashMap<String, T> map) {
super(enumClass, enums, map);
}
#Override
public T findEnum(String key) {
for (Map.Entry<String, T> entry : _enumsById.entrySet()) {
if (entry.getKey().equalsIgnoreCase(key)) { // magic line <--
return entry.getValue();
}
}
return null;
}
}
}
Usage:
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
public class JSON {
public static void main(String[] args) {
SimpleModule enumModule = new SimpleModule();
enumModule.setDeserializers(new CustomDeserializers());
ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(enumModule);
}
}
I used a modification of Iago Fernández and Paul solution .
I had an enum in my requestobject which needed to be case insensitive
#POST
public Response doSomePostAction(RequestObject object){
//resource implementation
}
class RequestObject{
//other params
MyEnumType myType;
#JsonSetter
public void setMyType(String type){
myType = MyEnumType.valueOf(type.toUpperCase());
}
#JsonGetter
public String getType(){
return myType.toString();//this can change
}
}
Here's how I sometimes handle enums when I want to deserialize in a case-insensitive manner (building on the code posted in the question):
#JsonIgnore
public void setDataType(DataType dataType)
{
type = dataType;
}
#JsonProperty
public void setDataType(String dataType)
{
// Clean up/validate String however you want. I like
// org.apache.commons.lang3.StringUtils.trimToEmpty
String d = StringUtils.trimToEmpty(dataType).toUpperCase();
setDataType(DataType.valueOf(d));
}
If the enum is non-trivial and thus in its own class I usually add a static parse method to handle lowercase Strings.
Deserialize enum with jackson is simple. When you want deserialize enum based in String need a constructor, a getter and a setter to your enum.Also class that use that enum must have a setter which receive DataType as param, not String:
public class Endpoint {
public enum DataType {
JSON("json"), HTML("html");
private String type;
#JsonValue
public String getDataType(){
return type;
}
#JsonSetter
public void setDataType(String t){
type = t.toLowerCase();
}
}
public String url;
public DataType type;
public Endpoint() {
}
public void setType(DataType dataType){
type = dataType;
}
}
When you have your json, you can deserialize to Endpoint class using ObjectMapper of Jackson:
ObjectMapper mapper = new ObjectMapper();
mapper.enable(SerializationFeature.INDENT_OUTPUT);
try {
Endpoint endpoint = mapper.readValue("{\"url\":\"foo\",\"type\":\"json\"}", Endpoint.class);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}

How to create custom Generic deserializer in Jackson?

I am looking to create a custom Deserializer in Jackson for set of Enum class. Since the behaviour of custom deserializer would be same for all enum. I want to make common Deserializer for all my enum class.
I tried making generic custom deserialize as follow:
class MyEnumDeserialize<T> extends JsonDeserializer<T> {
private Class beanClass;
public MyEnumDeserialize() {
}
public MyEnumDeserialize(Class beanClass) {
this.beanClass = beanClass;
}
#Override
public T deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
TreeNode node = jsonParser.getCodec().readTree(jsonParser);
T type = null;
try{
if(node.get("attr") != null){
// I don't know how to call ENUM static method here as I don't have context information here
if (type != null) {
return type;
}
}
}catch(Exception e){
type = null;
}
return null;
}
}
The problem is I want to call Enum static method inside the deserializer but unable to do so since I don't have any class/enum context information available.
Could you please help me know how could I achieve it.
I somehow managed to make following solution worked:
I created a module and modify EnumDeserializer as follow:
module.setDeserializerModifier(new BeanDeserializerModifier()
{
#Override public JsonDeserializer<?> modifyEnumDeserializer(DeserializationConfig config,
JavaType type, BeanDescription beanDesc, JsonDeserializer<?> deserializer)
{
if (beanDesc.getBeanClass().isEnum()) {
return new MyEnumDeserialize<>(beanDesc.getBeanClass());
}
return deserializer;
}
});
class MyEnumDeserialize<T extends Enum> extends JsonDeserializer<T> {
private Class beanClass;
public MyEnumDeserialize() {
}
public MyEnumDeserialize(Class beanClass) {
this.beanClass = beanClass;
}
#Override
public T deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
TreeNode node = jsonParser.getCodec().readTree(jsonParser);
T type = null;
try{
if(node.isValueNode()){
ValueNode valueNode = (ValueNode)node;
Method method = this.beanClass.getDeclaredMethod("get",short.class);
type = (T)method.invoke(null, Short.parseShort(valueNode.asText()));
if (type != null) {
return type;
}
}
}catch(Exception e){
type = null;
}
return type;
}
}
Though now, I am unable to provide Strict type checking ( creating instance with "<>").

Jackson - combine #JsonValue and #JsonSerialize

I am trying a combination of #JsonValue and #JsonSerialize. Let's start with my current container class:
public class Container {
private final Map<SomeKey, Object> data;
#JsonValue
#JsonSerialize(keyUsing = SomeKeySerializer.class)
public Map<SomeKey, Object> data() {
return data;
}
}
In this case, the custom serializer SomeKeySerializer is not used.
If I change the container as following, the serializer is called:
public class Container {
#JsonSerialize(keyUsing = SomeKeySerializer.class)
private final Map<SomeKey, Object> data;
}
However, this is not what I want, as this introduces another 'data' level in the output JSON.
Is it possible to combine #JsonValue and #JsonSerialize in some way?
I could always write another custom serializer for Container, which more or less does the same as the functionality behind #JsonValue. This would be more or less a hack, in my opinion.
Jackson version: 2.6.2
This combination seems to do what you want: make a Converter to extract the Map from the Container, and add #JsonValue to SomeKey itself to serialize it:
#JsonSerialize(converter = ContainerToMap.class)
public class ContainerWithFieldData {
private final Map<SomeKey, Object> data;
public ContainerWithFieldData(Map<SomeKey, Object> data) {
this.data = data;
}
}
public static final class SomeKey {
public final String key;
public SomeKey(String key) {
this.key = key;
}
#JsonValue
public String toJsonValue() {
return "key:" + key;
}
#Override
public String toString() {
return "SomeKey:" + key;
}
}
public static final class ContainerToMap extends StdConverter<ContainerWithFieldData, Map<SomeKey, Object>> {
#Override
public Map<SomeKey, Object> convert(ContainerWithFieldData value) {
return value.data;
}
}
#Test
public void serialize_container_with_custom_keys_in_field_map() throws Exception {
ObjectMapper mapper = new ObjectMapper();
assertThat(
mapper.writeValueAsString(new ContainerWithFieldData(ImmutableMap.of(new SomeKey("key1"), "value1"))),
equivalentTo("{ 'key:key1' : 'value1' }"));
}
I simply can't get annotating an accessor method of Container to DTRT at all easily, not in combination with #JsonValue. Given that #JsonValue on the container is basically designating a converter anyway (that is implemented by calling the annotated method), this is effectively what you're after, although not as pleasant as it seems it should be. (tried with Jackson 2.6.2)
(Something I learned from this: key serializers aren't like normal serializers, even though they implement JsonSerializer just the same. They need to call writeFieldName on the JsonGenerator, not writeString, for example. On the deserialization side, the distinction between JsonDeserializer and KeyDeserializer is spelled out, but not on the serialization side. You can make a key serializer from SomeKey with #JsonValue, but not by annotating SomeKey with #JsonSerialize(using=...), which surprised me).
Have you tried using #JsonSerialize(using = SomeKeySerializer.class) instead of keyUsing?
Doc for using() says:
Serializer class to use for serializing associated value.
...while for keyUsing you get:
Serializer class to use for serializing Map keys of annotated property
Tested it out myself and it works...
public class Demo {
public static class Container {
private final Map<String, String> data = new HashMap<>();
#JsonValue
#JsonSerialize(using = SomeKeySerializer.class)
public Map<String, String> data() {
return data;
}
}
public static class SomeKeySerializer extends JsonSerializer<Map> {
#Override
public void serialize(Map value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException {
jgen.writeStartObject();
jgen.writeObjectField("aKeyInTheMap", "theValueForThatKey");
jgen.writeEndObject();
}
}
public static void main(String[] args) throws JsonProcessingException {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.enable(SerializationFeature.INDENT_OUTPUT);
String s = objectMapper.writeValueAsString(new Container());
System.out.println(s);
}
}
This is the output when I'm NOT using com.fasterxml.jackson.annotation.JsonValue
{
"data" : {
"aKeyInTheMap" : "theValueForThatKey"
}
}
And this is the output when I'm using com.fasterxml.jackson.annotation.JsonValue
{
"aKeyInTheMap" : "theValueForThatKey"
}

Customize jackson unmarshalling behavior

I am using Jackson fasterxml for unmarshalling JSON. In my object there are two kinds of properties:Input properties and Calculated properties. In the input JSON, I get only input values.
The calculated values are actually dependent on input values. I have to populate these values before the object gets referred. So I am just checking if there are any hooks provided by Jackson so that I can do my calculations there. For example JAXB provides afterUnmarshal method to customize the unmarshaling behavior:
void afterUnmarshal(Unmarshaller u, Object parent)
But I could not find similar information about customizing Jackson. Are any such framework hooks provided by Jackson to customize the unmarshaling behavior?
I'd rather recommend to keep your model objects immutable by using constructor creators. That is, all the JSON values are passed to a constructor which would initialize the other calculated properties.
Anyway, if you want to customize an object after deserialization (without writing a deserializer for every type) you can modify the deserializer in a way that at the end it calls a special method(s) of a newly constructed instance. Here is an example which would work for all the classes that implements a special interface (one can consider using an annotation to mark the post construct methods).
public class JacksonPostConstruct {
public static interface PostConstructor {
void postConstruct();
}
public static class Bean implements PostConstructor {
private final String field;
#JsonCreator
public Bean(#JsonProperty("field") String field) {
this.field = field;
}
public void postConstruct() {
System.out.println("Post construct: " + toString());
}
#Override
public String toString() {
return "Bean{" +
"field='" + field + '\'' +
'}';
}
}
private static class PostConstructDeserializer extends DelegatingDeserializer {
private final JsonDeserializer<?> deserializer;
public PostConstructDeserializer(JsonDeserializer<?> deserializer) {
super(deserializer);
this.deserializer = deserializer;
}
#Override
protected JsonDeserializer<?> newDelegatingInstance(JsonDeserializer<?> newDelegatee) {
return deserializer;
}
#Override
public Object deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {
Object result = _delegatee.deserialize(jp, ctxt);
if (result instanceof PostConstructor) {
((PostConstructor) result).postConstruct();
}
return result;
}
}
public static void main(String[] args) throws IOException {
ObjectMapper mapper = new ObjectMapper();
SimpleModule module = new SimpleModule();
module.setDeserializerModifier(new BeanDeserializerModifier() {
#Override
public JsonDeserializer<?> modifyDeserializer(DeserializationConfig config,
BeanDescription beanDesc,
final JsonDeserializer<?> deserializer) {
return new PostConstructDeserializer(deserializer);
}
});
mapper.registerModule(module);
String json = "{\"field\":\"value\"}";
System.out.println(mapper.readValue(json, Bean.class));
}
}
Output:
Post construct: Bean{field='value'}
Bean{field='value'}
Let's assume that your JSON looks like this:
{
"input1" : "Input value",
"input2" : 3
}
And your POJO class looks like this:
class Entity {
private String input1;
private int input2;
private String calculated1;
private long calculated2;
...
}
In this case you can write a custom deserializer for your Entity class:
class EntityJsonDeserializer extends JsonDeserializer<Entity> {
#Override
public Entity deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException,
JsonProcessingException {
InnerEntity innerEntity = jp.readValueAs(InnerEntity.class);
Entity entity = new Entity();
entity.setInput1(innerEntity.input1);
entity.setInput2(innerEntity.input2);
entity.recalculate();
return entity;
}
public static class InnerEntity {
public String input1;
public int input2;
}
}
In above class you can see that Entity has a recalculate method. It could look like this:
public void recalculate() {
calculated1 = input1 + input2;
calculated2 = input1.length() + input2;
}
You can also move this logic to your deserializer class.
Now, you have to inform Jackson that you want to use your custom deserializer:
#JsonDeserialize(using = EntityJsonDeserializer.class)
class Entity {
...
}
The example below shows how to use these classes:
ObjectMapper mapper = new ObjectMapper();
System.out.println(mapper.readValue(json, Entity.class));
This program prints:
Entity [input1=Input value, input2=3, calculated1=Input value3, calculated2=14]

Dynamic polymorphic type handling with Jackson

I have a class hierarchy similar to this one:
public static class BaseConfiguration {
}
public abstract class Base {
private BaseConfiguration configuration;
public String id;
public BaseConfiguration getConfiguration() { ... }
public void setConfiguration(BaseConfiguration configuration) { ... }
}
public class A extends Base {
public static class CustomConfigurationA extends BaseConfiguration {
String filename;
String encoding;
}
CustomConfigurationA getConfiguration() { ... }
}
class B extends Base {
public static class CustomConfigurationB extends BaseConfiguration {
/* ... */
}
CustomConfigurationB getConfiguration() { ... }
}
And json input like this one (which I cannot change myself)
{
"id":"File1",
"configuration":{
"filename":"...",
"encoding":"UTF-8"
}
}
I am parsing the JSON in Java with Jackson like this
ObjectMapper mapper = new ObjectMapper();
value = mapper.readValue(in, nodeType);
I want to deserialize classes A, B and others from JSON using JAVA/Jackson. There are no type information embedded in JSON (and can't be). I can't use annotations on the classes (I don't own them) and I (believe) I can't use mixins since there are potentially arbitrary numbers of classes like A & B (and mixins are not dynamic). Good thing is that the deserializing code knows which is the correct custom class to use for deserializing (basically there is a known mapping from class to configuration class), but I do not know how make Jackson recognize this information when deserializing the JSON.
In short: I want to be able to resolve the deserialization type of the configuration object depending on the surrounding class type by setting whatever is necessary on ObjectMapper. How can this be achieved?
Apparently the answer was to implement something similar to the sixth solution posted at http://programmerbruce.blogspot.com/2011/05/deserialize-json-with-jackson-into.html, which uses unique JSON element names to identify the target type to deserialize to.
Good answer provided by Programmer Bruce!
I have a case of polymorphism in which I want to keep the domain objects as POJOs and not use dependencies on Jackson annotations.
Therefore I preffer to use a custom deserializer and a Factory for decising the type or intantiating the concrete classes.
Here is my code ...
(be aware that I have an Annotation Hierarchy which are in fact "User Tags" and not Java Annotations )
Here is the deserialization Method
public class AnnotationDeserializer extends StdDeserializer<Annotation> {
AnnotationDeserializer() {
super(Annotation.class);
}
#Override
public Annotation deserialize(JsonParser jp, DeserializationContext ctxt)
throws IOException, JsonProcessingException {
ObjectMapper mapper = (ObjectMapper) jp.getCodec();
ObjectNode root = (ObjectNode) mapper.readTree(jp);
Class<? extends Annotation> realClass = null;
Iterator<Entry<String, JsonNode>> elementsIterator = root.getFields();
while (elementsIterator.hasNext()) {
Entry<String, JsonNode> element = elementsIterator.next();
if ("type".equals(element.getKey())) {
realClass = AnnotationObjectFactory.getInstance()
.getAnnotationClass(element.getKey());
break;
}
}
if (realClass == null)
return null;
return mapper.readValue(root, realClass);
}
}
I had to do something similar, and ended up creating a generic polymorphic list serializer and deserialzer. Here is the deserialize that I think will work for you:
public class PolymorphicListDeserializer extends JsonDeserializer<List<?>> implements ContextualDeserializer {
private HashMap<String, Class> _typeMap = null;
private Class _elementType;
private static <T> List<T> getNewList(Class<T> clazz) {
return new ArrayList<T>();
}
#Override
public List<?> deserialize(final JsonParser jp, DeserializationContext ctxt) throws IOException {
final List list = getNewList(_elementType);
JsonToken nextToken = jp.getCurrentToken();
if (nextToken == JsonToken.START_OBJECT) {
if ( _typeMap.containsKey( currentFieldName )) {
list.add( _elementType.cast( ctxt.readValue( jp, _typeMap.get( currentFieldName ) ) ) );
}
nextToken = jp.nextToken();
} else if (currentFieldName != null && isEndToken(nextToken) && wrapperCount == 0) {
break;
} else {
nextToken = jp.nextToken();
}
}
return list;
}
public JsonDeserializer<List<?>> createContextual( DeserializationContext ctxt, BeanProperty property ) throws JsonMappingException {
//In Jackson 2.6.3, this method is called once per instance and the exception is never thrown
if ( _typeMap == null )
_typeMap = new HashMap<String, Class>();
else
throw new RuntimeException("Unsupported version of Jackson. Code assumes context is created once and only once.");
_elementType = property.getType().getContentType().getRawClass();
//For now, requiring XmlElements annotation to work. May add support for JsonElements (if needed) later.
for (XmlElement e : property.getAnnotation(XmlElements.class).value()) {
_typeMap.put(e.name(), e.type());
}
return this;
}
private static boolean isStartToken(JsonToken t) {
boolean result = false;
if (t == JsonToken.START_OBJECT) {
result = true;
} else if (t == JsonToken.START_ARRAY) {
result = true;
}
return result;
}
Above answers depicts a solution however lack what actually used annotations mean. If you are curious about what actually these annotation do, idea behind them & why they are required please go through the below link. Its explained very nicely in it. https://github.com/FasterXML/jackson-docs/wiki/JacksonPolymorphicDeserialization

Categories