SpringMVC返回JSON时NULL值的处理

1. 自定义类配置

解决方法和网上的 不太一样 因为SerializerProvider  为StdSerializerProvider的父类,直接从SerializerProvider .setNullValueSerializer()方法 不允许 所以通过子类StdSerializerProvider调用此方法

applicationContext.xml
            class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">  
         
             
                
                    
                        
                           text/plain;charset=UTF-8  
                           application/json;charset=UTF-8  
                      
 
                  
 
                    
                        
                  
 
              
     
           
 
       
 
   
   


ObjectMappingCustomer.java

    package com.interceptor;  
      
    import java.io.IOException;

import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.JsonProcessingException;
import org.codehaus.jackson.map.JsonSerializer;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.SerializerProvider;
import org.codehaus.jackson.map.ser.StdSerializerProvider;
      
    public class ObjectMappingCustomer extends ObjectMapper  
    {  
      
        public ObjectMappingCustomer()  
        {  
            super();  
            // 允许单引号  
            this.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);  
            // 字段和值都加引号  
            this.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);  
            // 数字也加引号  
            this.configure(JsonGenerator.Feature.WRITE_NUMBERS_AS_STRINGS, true);  
            this.configure(JsonGenerator.Feature.QUOTE_NON_NUMERIC_NUMBERS, true); 
            // 空值处理为空串  
            StdSerializerProvider sp = (StdSerializerProvider) this.getSerializerProvider();
            sp.setNullValueSerializer(new JsonSerializer(){

                @Override
                public void serialize(Object value, JsonGenerator jg,
                        SerializerProvider sp) throws IOException,
                        JsonProcessingException {
                     jg.writeString("");  
                }
                
            });
      
        }  
    } 
   

然后在springmvc  controller里加    @ResponseBody注解就可以了

需要jackson-all.jar

 

2. 注解配置

为了减少不必要的内容传输, 过滤null字段,可对返回的类加入注释来解决。

条件:

1.  spring MVC 3.X 支持注解

2. jackson-code.jar, jackson-mapper.jar 通常用jackson-all-xxx.jar 就行了

使用:

在需要序列化为json输出的类上增加, 例如:

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

@JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL)

public class XXXX{

}

 

3. 最新配置

@JsonInclude(value = Include.NON_NULL)
public class XXX implements Serializable{

}

http://sishuok.com/forum/posts/list/6996.html (深入浅出学Spring Web MVC )
http://my.oschina.net/angleshuai/blog/385123
http://blog.csdn.net/zdsdiablo/article/details/9429263

转载于:https://my.oschina.net/xinyuonline/blog/735025

你可能感兴趣的:(SpringMVC返回JSON时NULL值的处理)