1. 程式人生 > >Spring Boot JSON訊息轉換器

Spring Boot JSON訊息轉換器

package com.lawu.eshop.merchant.api.config;


import java.io.IOException;


import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;


import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializerProvider;


@Configuration
public class WebConfig {


//@Bean
//public MappingJackson2HttpMessageConverter customJackson2HttpMessageConverter() {
//MappingJackson2HttpMessageConverter jsonConverter = new MappingJackson2HttpMessageConverter();
//ObjectMapper objectMapper = new ObjectMapper();
//objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
//jsonConverter.setObjectMapper(objectMapper);
//return jsonConverter;
//}
//
//@Override
//public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
//converters.add(customJackson2HttpMessageConverter());
//super.addDefaultHttpMessageConverters(converters);
//}

@Bean
    @Primary
    @ConditionalOnMissingBean(ObjectMapper.class)
    public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder) {
        ObjectMapper objectMapper = builder.createXmlMapper(false).build();
        
        /*
         * 返回的JSON字串中含有我們並不需要的欄位,那麼當對應的實體類中不含有該欄位時,會丟擲一個異常,告訴你有些欄位沒有在實體類中找到
         */
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        
        SerializerProvider serializerProvider = objectMapper.getSerializerProvider();
        
        // 允許單引號 
        //objectMapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);  
        // 欄位和值都加引號  
        //objectMapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);  
        // 數字也加引號  
        //objectMapper.configure(JsonGenerator.Feature.WRITE_NUMBERS_AS_STRINGS, true);  
        //objectMapper.configure(JsonGenerator.Feature.QUOTE_NON_NUMERIC_NUMBERS, true);  
        
        //Null值輸出空字串
        serializerProvider.setNullValueSerializer(new JsonSerializer<Object>() {
            @Override
            public void serialize(Object o, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException, JsonProcessingException {
            jsonGenerator.writeString("");
            }
            
        });
        
        return objectMapper;
    }

}