packagecom.inspur.demo.json;importjava.text.SimpleDateFormat;importjava.util.ArrayList;importjava.util.Calendar;importjava.util.Date;importjava.util.HashMap;importjava.util.List;importjava.util.Map;importnet.sf.ezmorph.object.DateMorpher;importnet.sf.json.JSON;importnet.sf.json.JSONArray;importnet.sf.json.JSONObject;importnet.sf.json.JSONSerializer;importnet.sf.json.JsonConfig;importnet.sf.json.processors.JsonValueProcessor;importnet.sf.json.util.CycleDetectionStrategy;importnet.sf.json.util.JSONUtils;importnet.sf.json.util.PropertyFilter;/*** JSON-lib操作JSON数据*/
public classJsonLibCase {/*** 序列化*/
public staticString serialize() {
MyBean bean= newMyBean();
bean.setS("测试字符串");
Calendar calendar=Calendar.getInstance();
calendar.add(Calendar.HOUR_OF_DAY,-1);
bean.setD(calendar.getTime());
JsonConfig config= newJsonConfig();//防止自包含
config.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT);//Date类型转化
config.registerJsonValueProcessor(Date.class, newDateJsonValueProcessor());//过滤s3字段
config.setExcludes(new String[]{"s3"});//过滤值为null的字段
config.setJsonPropertyFilter(newPropertyFilter() {
@Overridepublic booleanapply(Object arg0, String arg1, Object value) {return value == null;
}
});
List list = new ArrayList();
list.add(bean);
Map> map = new HashMap>();
map.put("data", list);
JSON json=JSONSerializer.toJSON(map, config);
String result=json.toString();
System.out.println(json.toString());returnresult;
}/*** 反序列化*/
public static voiddeserialize() {try{//处理日期类型
JSONUtils.getMorpherRegistry().registerMorpher(new DateMorpher(new String[]{"yyyy-MM-dd HH:mm:ss"}));
String s=serialize();
Map> classMap = new HashMap>();
classMap.put("data", MyBean.class);
Map> map = (Map>) JSONObject.toBean(JSONObject.fromObject(s), Map.class, classMap);
System.out.println(map);//直接通过api获取相应数据
JSONObject obj =JSONObject.fromObject(s);
JSONArray data= obj.getJSONArray("data");
JSONObject bean= data.getJSONObject(0);
System.out.println(bean.getString("s"));//...
} catch(Exception e) {
e.printStackTrace();
}
}public static voidmain(String[] args) {
serialize();
deserialize();
}static class DateJsonValueProcessor implementsJsonValueProcessor {
@OverridepublicObject processArrayValue(Object value, JsonConfig arg1) {returnprocess(value);
}
@OverridepublicObject processObjectValue(String key, Object value, JsonConfig arg2) {returnprocess(value);
}privateObject process(Object value) {try{if (value instanceofDate) {
SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");returnsdf.format((Date) value);
}
}catch(Exception e) {
e.printStackTrace();
}return value == null ? "": value.toString();
}
}
}