JSON工具类

在平常工做中,发现这么一个小问题,作后台开发,给app返回的一个实体类,属性是有大小写区分的。但实际返回的时候却全都是小写的。而给PC返回的时候就都是有大小写区分的。java

这个是spring跳转的时候跟自动转换了。spring

咱们可使用一套json的工具类,进行强制转换json

package com.minxin.me.backstage.commons;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import net.sf.ezmorph.object.DateMorpher;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import net.sf.json.util.CycleDetectionStrategy;
import net.sf.json.util.JSONUtils;



/** 
 * <p>Title: Json工具类</p>
 */
public class JsonUtil{
	
	public static void renderJSON(HttpServletResponse res, String s) {
		render(res, s, "application/json;charset=utf-8");
	}
	
	private static void render(HttpServletResponse res, String s,
			String contextType) {
		try {
			res.setHeader("Pragma", "no-cache");
			res.setHeader("Cache-Control", "no-cache");
			res.setDateHeader("Expires", 0);
			res.setContentType(contextType);
			res.getWriter().write(s);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				res.flushBuffer();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}


	/**
	 * 
	 * 将java对象转换成json字符串
	 * 
	 * @param javaObj
	 * 
	 * @return
	 */

	public static String getJsonString4JavaPOJO(Object javaObj) {

		JSONObject json;

		json = JSONObject.fromObject(javaObj);

		return json.toString();

	}

	/**
	 * 
	 * 将java对象转换成json字符串,并设定日期格式
	 * 
	 */

	public static String getJsonString4JavaPOJO(Object javaObj,String dataFormat) {

		JSONObject json;

		JsonConfig jsonConfig = configJson(dataFormat);

		json = JSONObject.fromObject(javaObj, jsonConfig);

		return json.toString();

	}

	
	/**
	 * 
	 * 将java对象转换成json字符串,并设定日期格式
	 * 
	 */

	public static String getJsonArrayString4JavaPOJO(Object javaObj,String dataFormat) {

		JSONArray json;

		JsonConfig jsonConfig = configJson("yyyy-MM-dd HH:mm:ss");

		json = JSONArray.fromObject(javaObj, jsonConfig);

		return json.toString();

	}
	
	@SuppressWarnings("rawtypes")
	public static JSONObject objectcollect2json(List list, int total) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("total", total);
        map.put("rows", list);
        return JSONObject.fromObject(map);
    }

	
	/**
	 * 
	 * JSON 时间解析器具
	 * 
	 * @param datePattern
	 * 
	 * @return
	 */

	public static JsonConfig configJson(String datePattern) {

		JsonConfig jsonConfig = new JsonConfig();

		jsonConfig.setExcludes(new String[] { "" });

		jsonConfig.setIgnoreDefaultExcludes(false);

		jsonConfig.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT);

		jsonConfig.registerJsonValueProcessor(Date.class,new DateJsonValueProcessor(datePattern));

		return jsonConfig;

	}

	/**
	 * 
	 * 
	 * 
	 * @param excludes
	 * 
	 * @param datePattern
	 * 
	 * @return
	 */

	public static JsonConfig configJson(String[] excludes,

	String datePattern) {

		JsonConfig jsonConfig = new JsonConfig();

		jsonConfig.setExcludes(excludes);

		jsonConfig.setIgnoreDefaultExcludes(false);

		jsonConfig.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT);

		jsonConfig.registerJsonValueProcessor(Date.class,

		new DateJsonValueProcessor(datePattern));

		return jsonConfig;

	}
	/**
	 * 
	 * <p>
	 * Title:
	 * </p>
	 * <p>
	 * Description: 从一个JSON 对象字符格式中获得一个java对象
	 * </p>
	 * 
	 * @author Robin
	 * @param jsonString
	 * @param pojoCalss
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	public static Object getObject4JsonString(String jsonString, Class pojoCalss) {
		Object pojo = null;
		try {
			JSONObject jsonObject = JSONObject.fromObject(jsonString);
			pojo = JSONObject.toBean(jsonObject, pojoCalss);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return pojo;
	}

	/**
	 * 将json字符串转换成List<T>对象,处理日期类型
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public static <T> List<T> jsonToList(String json,Class clazz,String[] datePattern,Map classMap){
		JSONArray jsonArray = JSONArray.fromObject(json);
		JsonConfig jsonConfig = new JsonConfig();//参数设置
		jsonConfig.setRootClass(clazz);//设置array中的对象类型
		jsonConfig.setClassMap(classMap);
		String[] dateFormats = new String[] {"yyyy-MM-dd HH:mm:ss"}; 
		JSONUtils.getMorpherRegistry().registerMorpher(new DateMorpher(dateFormats));
		//将数组转换成T类型的集合 
		List<T> list = (List<T>)JSONArray.toCollection(jsonArray, jsonConfig);
		return list;		
	}
	
	/**
	 * 将json字符串转换成List<T>对象
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public static <T> List<T> jsonToList(String json,Class clazz){
		JSONArray jsonArray = JSONArray.fromObject(json);
		JsonConfig jsonConfig = new JsonConfig();//参数设置
		jsonConfig.setRootClass(clazz);//设置array中的对象类型
		//将数组转换成T类型的集合 
		List<T> list = (List<T>)JSONArray.toCollection(jsonArray, jsonConfig);
		return list;	
	}
}
@RequestMapping(value = "/fdsfr_pc")
	@ResponseBody
	public JxNewOpenCGResponse jsddregister(OpenPcCGRequest request, HttpServletResponse httpServletResponse) {
		logger.info("PC江西开户开始:" + request);
		JxNewOpenCGResponse response = new JxNewOpenCGResponse();
		// 对tokenid进行验证
		    各类验证
		}
		logger.info("开户响应参数:",response.toString());
		JsonUtil.renderJSON(httpServletResponse, JsonUtil.getJsonString4JavaPOJO(response));
		return null;
	}

使用上述方法,直接使用renderJSON方法,就能够将response对象 已大小写有区别的方式返回。数组

相关文章
相关标签/搜索