packagecom.inspur.demo.json;importjava.util.ArrayList;importjava.util.Calendar;importjava.util.HashMap;importjava.util.List;importjava.util.Map;importcom.alibaba.fastjson.JSON;importcom.alibaba.fastjson.JSONArray;importcom.alibaba.fastjson.JSONObject;importcom.alibaba.fastjson.TypeReference;importcom.alibaba.fastjson.serializer.SerializerFeature;/*** fastjson操作JSON数据*/
public classFastjsonCase {/*** 序列化*/
public staticString serialize() {
MyBean bean= newMyBean();
bean.setS("测试字符串");
Calendar calendar=Calendar.getInstance();
calendar.add(Calendar.HOUR_OF_DAY,-1);
bean.setD(calendar.getTime());
List list = new ArrayList();
list.add(bean);
Map> map = new HashMap>();
map.put("data", list);/** "yyyy-MM-dd HH:mm:ss" 设置日期格式,也可在类属性上使用@JSONField(format="yyyy-MM-dd HH:mm:ss")注解来设置
* SerializerFeature.WriteMapNullValue 输出值为null的字段
* SerializerFeature.WriteNullStringAsEmpty 字符串如果为null则输出""*/String result= JSON.toJSONStringWithDateFormat(map, "yyyy-MM-dd HH:mm:ss", SerializerFeature.WriteMapNullValue, SerializerFeature.WriteNullStringAsEmpty);
System.out.println(result);returnresult;
}/*** 反序列化*/
public static voiddeserialize() {
String s=serialize();
TypeReference>> type = new TypeReference>>(){};
Map> map =JSON.parseObject(s, type);
System.out.println(map);//直接通过api获取相应数据
JSONObject jsonObject =JSON.parseObject(s);
JSONArray JsonArray= jsonObject.getJSONArray("data");
JSONObject bean= JsonArray.getJSONObject(0);
System.out.println(bean.getString("s"));//...
}public static voidmain(String[] args) {
serialize();
deserialize();
}
}