Notes for MappingJackson 2HttpMessageConverter

Keywords: Spring JSON xml Java

Handle conversion of Date type fields to timestamps in Databases

There are two ways to solve the date conversion Json problem:

1. (Not recommended) Local modification, custom annotation to convert date type to Date type.

2. (strongly recommended) Global modification, configure in XML (Spring MVC) or in Application.Java startup classes (Spring boot, Spring cloud) using MappingJackson 2HttpMessageConverter.

Configured in Application.Java startup classes (Spring boot, Spring cloud):

@Bean
    public MappingJackson2HttpMessageConverter getMappingJackson2HttpMessageConverter() {
    	MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter = new MappingJackson2HttpMessageConverter();
    	//Set date format
    	ObjectMapper objectMapper = new ObjectMapper();
    	SimpleDateFormat smt = new SimpleDateFormat("yyyy-MM-dd");
    	objectMapper.setDateFormat(smt);
    	mappingJackson2HttpMessageConverter.setObjectMapper(objectMapper);
    	//Set Chinese encoding format
    	List<MediaType> list = new ArrayList<MediaType>();
    	list.add(MediaType.APPLICATION_JSON_UTF8);
    	mappingJackson2HttpMessageConverter.setSupportedMediaTypes(list);
    	return mappingJackson2HttpMessageConverter;
    }

Configured in XML (SpringMVC):

<mvc:annotation-driven>  
    <mvc:message-converters>  
        <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">  
    		<property name="objectMapper" ref="customObjectMapper"/>
        </bean>  
    </mvc:message-converters>  
</mvc:annotation-driven> 

Customize objectMapper:

public class CustomObjectMapper extends ObjectMapper {    
    
    public CustomObjectMapper() {    
        CustomSerializerFactory factory = new CustomSerializerFactory();    
        factory.addGenericMapping(Date.class, new JsonSerializer<Date>() {    
            @Override    
            public void serialize(Date value, JsonGenerator jsonGenerator,    
                    SerializerProvider provider) throws IOException, JsonProcessingException {    
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");    
                jsonGenerator.writeString(sdf.format(value));    
            }    
        });    
        this.setSerializerFactory(factory);    
    }    
}

Note: If you want a date field of a single bean to show the time, time, and second of the year, month, day, etc., you only need to add @JsonFormat(pattern="yyyy-MM-dd HH:mm:ss") to the get method of the corresponding date.

Set the handling of null values

MappingJackson2HttpMessageConverter Sets the handling of null values

Posted by bing_crosby on Fri, 21 Feb 2020 08:30:05 -0800