1

I have a POJO

class Product { String name; Size size; } 

So, I want to map a deserialize a JSON to my POJO. If I have both the attributes in my JSON, it is not a problem.

But in my case, sometimes size will not be a part of the JSON. There might be a third attribute 'type' based on which I will set my size. I do not want to include 'type' in my POJO. Are there any Jackson annotations which can do this?

2 Answers 2

3

write your custom Deserializers:

SimpleModule module = new SimpleModule("ProductDeserializerModule", new Version(1, 0, 0, null)); module.addDeserializer(Product.class, new ProductJsonDeserializer()); mapper = new ObjectMapper(); mapper.registerModule(module); 

//...

class ProductJsonDeserializer extends JsonDeserializer<Product> { @Override public Product deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { // handle here if exist a third attribute 'type' and create the product } } 

More info here: http://wiki.fasterxml.com/JacksonHowToCustomDeserializers

Sign up to request clarification or add additional context in comments.

1 Comment

Will try this. One more thing: Actually I am calling a WebResource, the JSON output of which I am trying to map to my POJO. Something like this: webResource.accept(MediaType.APPLICATION_JSON).get(Product.class) How do I register my ProductJsonDeserializer with this?
1

Found a pretty simple solution for this!

When a JSON attribute is attempted to be mapped to my POJO's attribute, it just checks whether a setter exists for it.

For example, if there is an attribute type in JSON, it will try to hit a method named setType(obj) in my POJO, regardless of whether there exists an attribute named type.

This worked for me! I simply set my other attributes inside this setter.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.