springMVC Json返回的封装 以及忽略null或改null为“”

一 json封装 

1.1maven依赖:


	<!-- fasterxml -->
		<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-databind</artifactId>
			<version>2.5.4</version>
		</dependency>
     <!-- jackson -->
		<dependency>
			<groupId>org.codehaus.jackson</groupId>
			<artifactId>jackson-mapper-asl</artifactId>
			<version>1.9.12</version>
		</dependency>

1.2封装类: 

package org.rgdata.common;

//import org.codehaus.jackson.annotate.JsonIgnore;
//import org.codehaus.jackson.map.annotate.JsonSerialize;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;

import java.io.Serializable;

/**
 * @Title:json返回封装
 * @Description:Comment for non-overriding methods
 * @author 张颖辉
 * @date 2018年2月9日下午1:35:49
 */
//@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
// 保证序列化json的时候,如果是null的对象,key也会消失
@JsonInclude(JsonInclude.Include.NON_NULL) 
public class JsonResult<T> implements Serializable {

	private static final long serialVersionUID = 1L;
	private int code;
	private String msg;
	private T data;

	private JsonResult(int code) {
		this.code = code;
	}

	private JsonResult(int code, T data) {
		this.code = code;
		this.data = data;
	}

	private JsonResult(int code, String msg, T data) {
		this.code = code;
		this.msg = msg;
		this.data = data;
	}

	private JsonResult(int code, String msg) {
		this.code = code;
		this.msg = msg;
	}

	// 使之不在json序列化结果当中
	@JsonIgnore
	public boolean isSuccess() {
		return this.code == ResultCode.SUCCESS.getCode();
	}

	public int getcode() {
		return code;
	}

	public T getData() {
		return data;
	}

	public String getMsg() {
		return msg;
	}

	public static <T> JsonResult<T> createBySuccess() {
		return new JsonResult<T>(ResultCode.SUCCESS.getCode(),ResultCode.SUCCESS.getDesc());
	}

	public static <T> JsonResult<T> createBySuccessMessage(String msg) {
		return new JsonResult<T>(ResultCode.SUCCESS.getCode(), msg);
	}

	public static <T> JsonResult<T> createBySuccess(T data) {
		return new JsonResult<T>(ResultCode.SUCCESS.getCode(),ResultCode.SUCCESS.getDesc(), data);
	}

	public static <T> JsonResult<T> createBySuccess(String msg, T data) {
		return new JsonResult<T>(ResultCode.SUCCESS.getCode(), msg, data);
	}

	public static <T> JsonResult<T> createByError() {
		return new JsonResult<T>(ResultCode.ERROR.getCode(), ResultCode.ERROR.getDesc());
	}

	public static <T> JsonResult<T> createByErrorMessage(String errorMessage) {
		return new JsonResult<T>(ResultCode.ERROR.getCode(), errorMessage);
	}

	public static <T> JsonResult<T> createByErrorCodeMessage(int errorCode, String errorMessage) {
		return new JsonResult<T>(errorCode, errorMessage);
	}

}

1.3 返回的code枚举:

package org.rgdata.common;

/**
 * @Title:返回code枚举
 * @Description:Comment for non-overriding methods
 * @author 张颖辉
 * @date 2018年2月9日下午1:35:49
 */
public enum ResultCode {
	SUCCESS(0, "SUCCESS"), ERROR(1, "ERROR"), NEED_LOGIN(10, "NEED_LOGIN"), ILLEGAL_ARGUMENT(2, "ILLEGAL_ARGUMENT");

	private final int code;
	private final String desc;

	ResultCode(int code, String desc) {
		this.code = code;
		this.desc = desc;
	}

	public int getCode() {
		return code;
	}

	public String getDesc() {
		return desc;
	}

}

返回效果:

131246_Bia9_2507499.png

1.4mvc json返回忽略null的配置(spring-mvc.xml中)

配置消息转换器:

<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">
					<bean class="org.rgdata.converter.JsonObjectMapper"></bean>
				</property> 
			</bean>
		</mvc:message-converters>
	</mvc:annotation-driven>

效果:

131045_Ma2P_2507499.png

二 扩展:将返回的json中的null替换换为“”

2.1先实现一个转换类:

package org.rgdata.converter;

import java.io.IOException;

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

/**
 * @Title:JsonObjectMapper 转换器
 * @Description:Comment for created type
 * @author 张颖辉
 * @date 2018年3月21日上午10:12:56
 * @version 1.0
 */
public class JsonObjectMapper extends ObjectMapper{
	private static final long serialVersionUID = 1L;
	public JsonObjectMapper() {
		super();
		this.getSerializerProvider().setNullValueSerializer(new JsonSerializer<Object>() {
			@Override
			public void serialize(Object value, JsonGenerator jg, SerializerProvider sp)
					throws IOException, JsonProcessingException {
				jg.writeString("");
			}
		});
	}
}

2.2将上面关于jackson的配置改为下面的样子 

<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"><bean class="com.fasterxml.jackson.databind.ObjectMapper"><property name="serializationInclusion"><value type="com.fasterxml.jackson.annotation.JsonInclude.Include">NON_NULL</value></property></bean></property>-->
            <property name="objectMapper">
                <bean class="org.rgdata.converter.JsonObjectMapper"></bean>
            </property>
        </bean>
    </mvc:message-converters>
</mvc:annotation-driven>

效果:

131009_SqEC_2507499.png

坑:

关于忽略null的坑

忽略null属性,或者指定忽略的属性注解 @JsonIgnore @JsonSerialize  @JsonInclude相关的坑

codehaus

如果代码引入的是 

import org.codehaus.jackson.annotate.JsonIgnore;
import org.codehaus.jackson.map.annotate.JsonSerialize;

但是pom.xml中依赖了(spring 使用的4.1.7)

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.5.4</version>
</dependency>

返回:

143335_0aiV_2507499.png

就会出现 @JsonIgnore @JsonSerialize注解都无效,删除上面的依赖则测试有效

所以如果使用codehaus包中的忽略注解则不能依赖fasterxml包,效果如下

140738_Rclg_2507499.png

fasterxml

引入了上面的fasterxml依赖,@JsonIgnore有效,但是@JsonInclude(JsonInclude.Include.NON_NULL) 无效。(这里没有配置上文1.4,因为1.4是全局配置,与是否使用注解无关)。

 

 

转载于:https://my.oschina.net/iyinghui/blog/1632341

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值