JSON工具类

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

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

我们可以使用一套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对象 已大小写有区别的方式返回。

转载于:https://my.oschina.net/u/2543341/blog/847181

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值