远方蔚蓝
一刹那情真,相逢不如不见

文章数量 126

访问次数 199888

运行天数 1437

最近活跃 2024-10-04 23:36:48

进入后台管理系统

Spring返回json格式配置


import java.io.IOException;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializerProvider;
/**
 * json返回的null转为空字符串
 * @author wst 2018-10-29 上午11:37:36
 *
 */
public class ObjectMappingCustomer extends ObjectMapper {
	private static final long serialVersionUID = 1L;
	public ObjectMappingCustomer() {
		super();
		// 允许单引号
		this.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, false);
		// 允许字段可以不用双引号
		this.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, false);
		// 数字作为字符串类型输入
		this.configure(JsonGenerator.Feature.WRITE_NUMBERS_AS_STRINGS, false);
		// 特殊数字类型(float/double values are output as quoted strings)
		this.configure(JsonGenerator.Feature.QUOTE_NON_NUMERIC_NUMBERS, false);
		// 空值处理为空串
		this.getSerializerProvider().setNullValueSerializer(
			new JsonSerializer<Object>() {
				@Override
				public void serialize(Object value, JsonGenerator jg, SerializerProvider sp) throws IOException, JsonProcessingException {
					jg.writeString("");
				}
			});
	}
}
在application中配置
    <mvc:annotation-driven>
        <mvc:message-converters>
            <bean class="org.springframework.http.converter.StringHttpMessageConverter">
                <property name="supportedMediaTypes">
                    <list>
                        <value>text/plain;charset=UTF-8</value>
                        <value>text/html;charset=UTF-8</value>
                    </list>
                </property>
            </bean>
            <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
                <property name="supportedMediaTypes">
                    <list>
                        <value>application/json;charset=UTF-8</value>
                    </list>
                </property>
                <property name="objectMapper">  
                    <!-- ObjectMappingCustomer -->
	                <bean class="com.mov.mw.handler.ObjectMappingCustomer"></bean>  
	            </property> 				
            </bean>
        </mvc:message-converters>
    </mvc:annotation-driven>