Search code examples
javajsonspring-bootjacksonobjectmapper

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


Solution

  • 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;