spring mvc3 Jackson输出null转为空串两种解决方法

      之前因为返回到iPhone客户端和android客户端的json格式中许多值是null值,界面去key显示出来的值就为null,很不友好。手机端开发者表示要把null转为“”暂时没有办法。

于是就交给了服务器端,在网上找了http://wuliaolll.iteye.com/blog/1868205这篇文章,我们采用的是springmvc3.0.5.release和spring3.0.5这个版本。对于文章上的方法试过几次,改过几次,都无效,初步认为是springmvc或者spring的bug,如果有知道原因的请回复我,让大家都了解了解。如果大家用http://wuliaolll.iteye.com/blog/1868205 这篇文章的方法无效,不放试试我的解决方法。

最后解决方案如下:


ObjectMappingCustomer.java

package javacommon.util;

import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.JsonProcessingException;
import org.codehaus.jackson.map.JsonSerializer;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.SerializerProvider;

import java.io.IOException;

/**
 * Date: 13-11-13
 * Time: 上午9:01
 */
public class ObjectMappingCustomer extends ObjectMapper {

    public ObjectMappingCustomer() {
        super();
        // 空值处理为空串
        this.getSerializerProvider().setNullValueSerializer(new JsonSerializer() {

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

    }
}
 
  
JsonUtil.java 这个类是我从项目抽出来的,方便直接使用. 后面我会贴出项目中用的类,方便借鉴运用

package com.test;

import java.io.IOException;

import javax.servlet.http.HttpServletResponse;

import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;

public class JsonUtil {
    private static ObjectMappingCustomer objectMappingCustomer = new ObjectMappingCustomer();
    private static ObjectMapper objectMapper;

    /**
     * 把jackson null转为""串
     * @param response 
     * @param object  
     */
	@SuppressWarnings("unused")
	public static void WriteNullToString(HttpServletResponse response,Object object) {
    	response.setContentType("application/json");
        try {
        	if(false) {//如果为true,表示允许返回的json为null,具体值可以配置到配置文件然后读取,以后要改就不用改源码了
        		if (objectMapper == null) {
        			objectMapper = new ObjectMapper();
        		}
        		response.getWriter().write(objectMapper.writeValueAsString(object));
        	}else {
        		response.getWriter().write(objectMappingCustomer.writeValueAsString(object));
        	}
		} catch (JsonGenerationException e) {
			e.printStackTrace();
		} catch (JsonMappingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
    }
}
有了上面两部就可以运用了,贴一个实际代码出来参考.

运用到实际项目中的实现

MobileResult.java

package com.wallaw.portal.model;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javacommon.util.ObjectMappingCustomer;
import javacommon.util.PublicCode;
import javacommon.util.StringUtil;

import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;

/**
 * Date: 13-4-26
 * Time: 下午1:56
 * 返回手机客户端通用类
 */
public class MobileResult {

    private String resultCode;
    private String returnMsg;
    private Map resultObject;
    
    private static ObjectMappingCustomer objectMappingCustomer;
    private static ObjectMapper objectMapper;
    private static final Logger LOG = Logger.getLogger(MobileResult.class);
    public MobileResult() {
        resultObject = new HashMap();
    }

    public String getResultCode() {
        return resultCode;
    }

    public void setResultCode(String resultCode) {
        this.resultCode = resultCode;
    }

    public String getReturnMsg() {
        return returnMsg;
    }

    public void setReturnMsg(String returnMsg) {
        this.returnMsg = returnMsg;
    }

    public Map getResultObject() {
        return resultObject;
    }

    public void setResultObject(Map resultObject) {
        this.resultObject = resultObject;
    }
    
	public static void setObjectMappingCustomer(
			ObjectMappingCustomer objectMappingCustomer) {
		MobileResult.objectMappingCustomer = objectMappingCustomer;
	}

	public void WriteJsonToResponse(HttpServletResponse response) {
    	response.setContentType("application/json");
        try {
        	if(StringUtil.toBoolean(PublicCode.getCommConfigMap().get("enable.jsonnull"), false)) {
        		if (objectMapper == null) {
        			objectMapper = new ObjectMapper();
        		}
        		response.getWriter().write(objectMapper.writeValueAsString(this));
        	}else {
        		response.getWriter().write(objectMappingCustomer.writeValueAsString(this));
        	}
		} catch (JsonGenerationException e) {
			LOG.error("WriteJsonToResponse查询失败:", e);
		} catch (JsonMappingException e) {
			LOG.error("WriteJsonToResponse查询失败:", e);
		} catch (IOException e) {
			LOG.error("WriteJsonToResponse查询失败:", e);
		}
    }
}


贴一个controller,看了就应该明白上面的代码
/*
 * Powered By [rapid-framework]
 * Web Site: http://www.rapid-framework.org.cn
 * Google Code: http://code.google.com/p/rapid-framework/
 * Since 2008 - 2013
 */


package com.wallaw.portal.controller;

import java.util.List;

import javacommon.base.BaseRestSpringController;
import javacommon.util.CollectionUtil;
import javacommon.util.Constants;

import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import com.wallaw.portal.model.MobileResult;
import com.wallaw.portal.model.Test;
import com.wallaw.portal.service.ProductStatusManager;
import com.wallaw.portal.vo.query.ProductStatusQuery;

/**
 * @version 1.0
 * @since 1.0
 */

@Controller
@RequestMapping("/test")
public class TestController extends BaseRestSpringController{
	
 	private ProductStatusManager productStatusManager;

 	public void setProductStatusManager(ProductStatusManager productStatusManager) {
		this.productStatusManager = productStatusManager;
	}
	   
	
	/*-----------------------------------------------------手机端接口--------------------------------------------------------------------*/
	
	/**
	 * 每日推荐列表
	 */
	@RequestMapping(value="mobile/list")//去除了@ResponseBody
	public void list(ModelMap model,ProductStatusQuery productStatusquery, HttpServletResponse response){
		MobileResult mobileResult = new MobileResult();
		mobileResult.setResultCode(Constants.FAILURE_CODE);
		mobileResult.setReturnMsg(Constants.FAILURE);
		//查金融推荐产品
		List productList = productStatusManager.getProductListWithRecommend(productStatusquery);
		//计算总数
		int count = CollectionUtil.isEmpty(productList)?0:productList.size();
		if(count!=0){
			mobileResult.setResultCode(Constants.SUCCESS_CODE);
			mobileResult.setReturnMsg(Constants.SUCCESS);
			mobileResult.getResultObject().put("productList", productList);
			mobileResult.getResultObject().put("count", count);
		}
		mobileResult.WriteJsonToResponse(response);//利用response.getWriter().write(String)把json返回给手机端
	}
	
}

返回结果如下图:

spring mvc3 Jackson输出null转为空串两种解决方法_第1张图片

网上没有找到相关的实现,自己实现之后就写下来了,希望对大家有用。

你可能感兴趣的:(spring,mvc,spring)