How to ignore pojo annotations while using Jackson ObjectMapper?
Asked Answered
B

3

14

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?

Blackout answered 28/7, 2015 at 14:58 Comment(0)
B
13

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!

Blackout answered 28/7, 2015 at 15:14 Comment(2)
When I wrote this, I got The method configure(MapperFeature, boolean) in the type ObjectMapper is not applicable for the arguments (DeserializationConfig.Feature, boolean). Any suggestions?Lamphere
@MahmoudMubarak This answer is for codehaus version of jackson. See above answer if you are using fasterxml?Blackout
H
24

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

ObjectMapper mapper = new ObjectMapper().configure(MapperFeature.USE_ANNOTATIONS, true);
Hiles answered 13/5, 2016 at 11:11 Comment(1)
or mapper.disable(MapperFeature.USE_ANNOTATIONS);Warenne
B
13

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!

Blackout answered 28/7, 2015 at 15:14 Comment(2)
When I wrote this, I got The method configure(MapperFeature, boolean) in the type ObjectMapper is not applicable for the arguments (DeserializationConfig.Feature, boolean). Any suggestions?Lamphere
@MahmoudMubarak This answer is for codehaus version of jackson. See above answer if you are using fasterxml?Blackout
A
0
new ObjectMapper().configure(MapperFeature.USE_ANNOTATIONS, true);

and

new ObjectMapper().disable(MapperFeature.USE_ANNOTATIONS);

are now deprecated. You should use:

JsonMapper.builder()
            .configure(MapperFeature.USE_ANNOTATIONS, false)
            .build()

or

JsonMapper.builder()
            .disable(MapperFeature.USE_ANNOTATIONS)
            .build();
Anelace answered 5/8 at 8:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.