springMvc的json转化器实现json返回格式的改变

在springMvc控制器中,返回对象给前端的时候,前端可能会要求给数字类型的字段加双引号,日期格式的转化,不希望返回null等情况,可以采用springMvc的转化器进行实现,具体配置如下:

1.在springMvc配置文件中加入如下配置:ObjectMappingCustomer是一个自定义转化器,需要实现ObjectMapper接口

<mvc:annotation-driven>
	    <mvc:message-converters>
	    	<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
			   <property name="objectMapper">
                    <bean class="com.lantaiyuan.ebus.custom.util.ObjectMappingCustomer"></bean>
               </property>
		    </bean>
	   </mvc:message-converters>
</mvc:annotation-driven>

2.新建一个ObjectMappingCustomer去实现ObjectMapper接口

package com.lantaiyuan.ebus.custom.util;

import java.io.IOException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.core.JsonProcessingException;

public class ObjectMappingCustomer extends ObjectMapper {

    /**
     * 
     */
    private static final long serialVersionUID = -6401263387943827254L;

    public ObjectMappingCustomer() {
	super();
	
        // 数字也加引号
        this.configure(JsonGenerator.Feature.WRITE_NUMBERS_AS_STRINGS, true);
        this.configure(JsonGenerator.Feature.QUOTE_NON_NUMERIC_NUMBERS, true);
        
	//以下方法是将返回的json对象中的null替换为“”,如果需要替换成其他信息,可以在这边自定义
	this.getSerializerProvider().setNullValueSerializer(new com.fasterxml.jackson.databind.JsonSerializer<Object>() {
	    @Override
	    public void serialize(Object arg0, JsonGenerator jg, SerializerProvider arg2)
		    throws IOException, JsonProcessingException {
		 jg.writeString("");
	    }
	});

    }
}

3.配置前后效果对比:

配置前:

配置后:

转载于:https://my.oschina.net/u/2988360/blog/822813

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值