madhairsilence
madhairsilence

Reputation: 3880

Two instances of ObjectMapper

Is there a way to create two instances of ObjectMapper for different purpose.

Modified ObjectMapper

    @Component
    class MyObjectMapper extends ObjectMapper{
      public MyObjectMapper(){
        super();
      }

    public MyObjectMapper(MyObjectMapper om) {
        super(om);
     }

    @Override
    public MyObjectMapper copy() {
        return new MyObjectMapper(this);
     }
   }

Now use it as follows

@Autowired ObjectMapper objectMapper; //performs standard serialization
@Autowire MyObjectMapper myMapper; //i can add custom filters in thiis mapper.

I tried a similar setup but the custom mapper actually affects the original mapper all the rest controllers throw JSON parse error: Unrecognized field

Edit: Not sure if this point is very important but still adding it Am using spring-boot-starter-json

Upvotes: 1

Views: 2097

Answers (2)

madhairsilence
madhairsilence

Reputation: 3880

OK. Combining with Answer from Aniket figured out what is wrong and still looking for some more explanation.

Instead of instantiating the ObjectMapper as new ObjectMapper(). Building it with Mapper fixed it.

So, two have multiple instance of ObjectMapper

@Primary
@Bean
public ObjectMapper objectMapper(){
   return new Jackson2ObjectMapperBuilder()
                .build();
}

@Bean("customMapper")
public ObjectMapper customMapper(){
  ObjectMapper customMapper = new Jackson2ObjectMapperBuilder().build();
     mapper.<your customization , filters, providers etc;>
     return mapper;
}

The @Primary will be used by in all default cases i.e When you simply @Autowire or the default serialization applied to your Response/Request Body by your controller.

To use your Custom Mapper, explicitly use with the Bean ID.

@Autowired @Qualifier("customMapper") ObjectMapper mapper;

Upvotes: 0

Aniket Sahrawat
Aniket Sahrawat

Reputation: 12937

And that's exactly where you should use @Qualifier annotation.

This annotation may be used on a field or parameter as a qualifier for candidate beans when autowiring. It may also be used to annotate other custom annotations that can then in turn be used as qualifiers.

Upvotes: 2

Related Questions