JSONObject 处理问题
相关博客参考:https://www.cnblogs.com/free-dom/p/5801866.html
json-lib 和google gson 的使用
TorgCadre res=new TorgCadre(); res.setName(torgcadre.getName());//姓名 res.setMarriage(torgcadre.getMarriage()); res.setWeight(torgcadre.getWeight()); res.setSex(torgcadre.getSex()); res.setJkInfo(torgcadre.getJkInfo()); res.setBirthday(torgcadre.getBirthday());
//JSONObject 处理日期字段问题,把对象转换成json数据 JsonConfig config1 = new JsonConfig(); config1.registerJsonValueProcessor(Date.class, new JsonDateValueProcessor("yyyyMMdd")); JSONObject jsonObject= JSONObject.fromObject(res,config1);
//GSON把对象转换成json数据
Gson gson = new GsonBuilder().setDateFormat("yyyyMMdd").create();
String str = gson.toJson(res);
JSONArray jsonArray=JSONArray.fromObject(str);
//JSONArray把集合转换成json数据
List<DepositWork> list=new ArrayList<DepositWork>();
JsonConfig config1 = new JsonConfig();
config1.registerJsonValueProcessor(Date.class, new JsonDateValueProcessor("yyyyMMdd"));
JSONArray jsonArray=JSONArray.fromObject(list,config1);
package com.diamond.web.utils; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; import net.sf.json.JsonConfig; import net.sf.json.processors.JsonValueProcessor; /** * 对象转json日期处理类 * ClassName: JsonDateValueProcessor * @Description: TODO * @author HJJ * @date 2017-12-18 */ public class JsonDateValueProcessor implements JsonValueProcessor { private String format ; public JsonDateValueProcessor() { super(); } public JsonDateValueProcessor(String format) { super(); this.format = format; } public Object processArrayValue(Object paramObject, JsonConfig paramJsonConfig) { return process(paramObject); } public Object processObjectValue(String paramString, Object paramObject, JsonConfig paramJsonConfig) { return process(paramObject); } private Object process(Object value){ if(value instanceof Date){ SimpleDateFormat sdf = new SimpleDateFormat(format,Locale.CHINA); return sdf.format(value); } return value == null ? "" : value.toString(); } }