Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to ignore pojo annotations while using Jackson ObjectMapper?

Tags:

java

json

jackson

I've a POJO with Jackson annotations

     public class Sample{

        private String property1;

        @JsonIgnore
        private String property2;

        //...setters getters

     }

So, when Jackson library is used for automarshalling by other frameworks such as RestEasy these annotations help guide the serialization and deserilization process.

But when I want to explicitly serialize using ObjectMapper mapper = new ObjectMapper(), I don't want those annotations to make any effect, instead I will configure the mapper object to my requirement.

So, how to make the annotations not make any effect while using ObjectMapper?

like image 604
pinkpanther Avatar asked Jul 28 '15 14:07

pinkpanther


People also ask

How do I ignore properties in ObjectMapper?

ObjectMapper; ObjectMapper objectMapper = new ObjectMapper(); objectMapper. configure(DeserializationFeature. FAIL_ON_UNKNOWN_PROPERTIES, false); This will now ignore unknown properties for any JSON it's going to parse, You should only use this option if you can't annotate a class with @JsonIgnoreProperties annotation.

How do you tell Jackson to ignore a field during deserialization?

Overview So when Jackson is reading from JSON string, it will read the property and put into the target object. But when Jackson attempts to serialize the object, it will ignore the property. For this purpose, we'll use @JsonIgnore and @JsonIgnoreProperties.

How do I ignore properties in Jackson?

The Jackson @JsonIgnore annotation can be used to ignore a certain property or field of a Java object. The property can be ignored both when reading JSON into Java objects and when writing Java objects into JSON.

How do I ignore null values in Jackson?

In Jackson, we can use @JsonInclude(JsonInclude. Include. NON_NULL) to ignore the null fields.


2 Answers

Hi if you are using com.fasterxml.jackson then code is -

ObjectMapper mapper = new ObjectMapper().configure(MapperFeature.USE_ANNOTATIONS, true);
like image 175
Krishnendu Avatar answered Oct 06 '22 00:10

Krishnendu


Configure your ObjectMapper not to use those Annotations, like this:

ObjectMapper objectMapper = new ObjectMapper().configure(
                 org.codehaus.jackson.map.DeserializationConfig.Feature.USE_ANNOTATIONS, false)
                    .configure(org.codehaus.jackson.map.SerializationConfig.Feature.USE_ANNOTATIONS, false);

This works!

like image 29
pinkpanther Avatar answered Oct 06 '22 01:10

pinkpanther