spring mvc custom converter for json data

Follow the post Restful application with Spring MVCYou will see some data with null value still generate on json data. How we can ignore this kind of property. Also how we can deal with some custom datatype as joda-time or joda-money

This guide will help you over come the above issues

1. Joda DateTime JSON serializer 

I write a serializer for Joda DateTime type.

public class JodaTimeSerializer extends JsonSerializer {
  @Override
  public void serialize(DateTime datetime, JsonGenerator jg,
      SerializerProvider provider) throws IOException,
      JsonProcessingException {
    SimpleDateFormat sf = new SimpleDateFormat("yyyyMMdd");
    jg.writeString(sf.format(datetime.toDate()));
  }
}

2. Custom Jackson Mapper

Follow is code of class CustomJacksonMapper. This class will register Joda DateTime serializer and only serialize property with non-null value.

@Component
@Qualifier(value = "objectMapper")
public class CustomJacksonMapper extends
    com.fasterxml.jackson.databind.ObjectMapper {

  private static final long serialVersionUID = 6676639462863745282L;

  public CustomJacksonMapper() {
    SimpleModule module = new SimpleModule();
    module.addSerializer(DateTime.class, new JodaTimeSerializer());
    this.registerModule(module);
    this.setSerializationInclusion(Include.NON_NULL);
  }

}

@Component and @Qualifier: these annotation allow spring find and register as bean with bean name objectMapper
3. Config converter in Spring MVC

To config custom converter in Spring MVC i create a class  as below

public class ConfigConverter {

    public ConfigConverter() {
    }

    private RequestMappingHandlerAdapter requestMappingHandlerAdapter;

    private CustomJacksonMapper objectMapper;

    @PostConstruct
    public void init() {
        List<HttpMessageConverter<?>> messageConverters = requestMappingHandlerAdapter.getMessageConverters();
        for (HttpMessageConverter<?> messageConverter : messageConverters) {
            if (messageConverter instanceof MappingJackson2HttpMessageConverter) {
                MappingJackson2HttpMessageConverter m = (MappingJackson2HttpMessageConverter) messageConverter;
                m.setObjectMapper(objectMapper);
            }
        }
    }

    public RequestMappingHandlerAdapter getRequestMappingHandlerAdapter() {
        return requestMappingHandlerAdapter;
    }
    //this autowire will work cause in xml we have a config <annotation-driven />
    @Autowired
    public void setRequestMappingHandlerAdapter(RequestMappingHandlerAdapter requestMappingHandlerAdapter) {
        this.requestMappingHandlerAdapter = requestMappingHandlerAdapter;
    }

    public CustomJacksonMapper getObjectMapper() {
        return objectMapper;
    }

    @Autowired
    public void setObjectMapper(CustomJacksonMapper objectMapper) {
        this.objectMapper = objectMapper;
    }

}

After that define bean in Spring servlet XML config file

<context:component-scan base-package="com.devjav.util"/>

<beans:bean id="configConverter"
class="com.devjav.util.ConfigConverter" />

This config will allow Spring register custom converter for JSON data.

4. Demo

  • Request:  GET: http://localhost:8080/spring-rest/contact/1
  • Response:{"success":true,"data":{"id":1,"fname":"Thinh","lname":"Pham","mname":"Thai","phone":"435435454","createDate":"20140327"}}

As you see createDate now will generate with format yyyyMMdd
5. Source code: spring-rest

Leave a Reply