日期:2014-05-16  浏览次数:20325 次

关于http接口开发中json格式数据编码问题处理

关于http接口开发中json格式数据编码问题处理

在实际工作中,接口很多时候返回json格式,但有时返回的格式会有编码问题


假设如下接口:http://service.test.com/interface/getData_test.jsp

返回如下是正常的。

[{"name":"\u8fd9\u662f\u4e2a\u6d4b\u8bd5"}]

但有时返回是这样的。

[{"name":"这是个测试"}]  

这个是错误的。

解决办法:
主要是jar包引起的。

正确jar包如下:

json-2.2.1.jar
json-lib-2.4-jdk15.jar


如果:如下jar包 则有编码问题

json-parser_fat.jar
json-lib-2.4-jdk15.jar


测试代码如下:

<%@page import="org.apache.commons.lang.math.NumberUtils"%><%@page import="java.net.URLEncoder"%><% 
	response.setContentType("text/html;charset=UTF-8");
	response.setHeader("Cache-Control", "no-cache");
	response.setHeader("Cache-Control", "no-store");
	response.setDateHeader("Expires", 0);
	response.setHeader("Pragma", "no-cache");
	%><%@page import="java.sql.Timestamp"%><%@page contentType="text/html; charset=UTF-8"
%><%@ page import="java.util.*,
java.io.IOException,java.util.regex.*,
org.springframework.web.context.WebApplicationContext,
org.springframework.web.context.support.WebApplicationContextUtils,
org.apache.commons.lang.StringUtils,net.sf.json.*"
%><%=getJX_Content()%><%!
/**
	 * 测试
	 * @return
	 */
	public static String getJX_Content()
	{
	

		String ret="";
		JSONArray jsonArray=new JSONArray();
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("name","这是个测试");
		jsonArray.add(jsonObject);
	    ret=jsonArray.toString();
	    


	    		
	    return ret;
	}
	
%>


相关json包下载:  http://download.csdn.net/detail/5iasp/6198283