0

In Spring boot, is it possible to have many different versions of gson or Jackson http converters and use them dynamically whenever I need a specific type of data format?

Kingj
  • 1
  • 1
  • Hi Kingj, could you please provide more information about what you want to do? for example your `Converter`, `Objects that you need to serialize as null or not dinamically` codes? – Jonathan JOhx Oct 07 '19 at 15:29
  • One of the reason why its null is , its not able to parse the object and throws an exception which you caught and supress ( may not be intentional). Add @JsonIgnoreProperties(ignoreUnknown=true) on top of your class – madhairsilence Oct 07 '19 at 15:32
  • @Kingj done, I added an answer that you might implement it. – Jonathan JOhx Oct 07 '19 at 16:28
  • Sometimes you want to serialize nulls for the same entities or these are different entities? – Garis M Suero Oct 07 '19 at 16:32

1 Answers1

1

You have to create two beans for GsonHttpMessageConverter the first one with settings by default and second one with setting for serializing nulls by following way:

@Bean
public GsonHttpMessageConverter gsonHttpMessageConverter() {
    return buildGsonHttpMessageConverter(MapperUtil.getGsonInstance());
}

@Bean
public GsonHttpMessageConverter gsonHttpMessageConverterWithNulls() {
    return buildGsonHttpMessageConverter(MapperUtil.getGsonInstanceSerializeNulls());
}

private GsonHttpMessageConverter buildGsonHttpMessageConverter(final Gson gson) {
    final GsonHttpMessageConverter converter = new GsonHttpMessageConverter();
    converter.setGson(gson);
    return converter;
}

And when you want to use one of them then call @Qualifier("someBean") annotation. by following way:

@Autowired
@Qualifier("gsonHttpMessageConverter")
GsonHttpMessageConverter gsonHttpMessageConverter;

@Autowired
@Qualifier("gsonHttpMessageConverterWithNulls")
GsonHttpMessageConverter gsonHttpMessageConverterWithNulls;
Jonathan JOhx
  • 5,784
  • 2
  • 17
  • 33