map与json的转换
2019-02-25 本文已影响0人
站在海边看远方
使用fastjson实现map与json的互相转换
1.map转json
public class JsonTest {
public static void main(String[] args) {
HashMap<String, String> map = new HashMap<>();
map.put("code","111");
map.put("desc","22222");
JSONObject json = JSONObject.parseObject(JSON.toJSONString(map));
System.out.println(json);
}
}
2.json转map
public class JsonTest {
public static void main(String[] args) {
String json1="{\"code\":\"111\",\"desc\":\"22222\"}";
Map map1 = JSON.parseObject(json1);
for (Object obj:map1.keySet()){
System.out.println(map1.get(obj));
}
}
}
3.关于一些时间格式的转换
new Date()是java.util.Date
这个里面是时间处理的参数
JSON.toJSONString(map,
SerializerFeature.DisableCircularReferenceDetect,
SerializerFeature.WriteDateUseDateFormat)
public class JsonTest {
public static void main(String[] args) {
HashMap<String, Date> map = new HashMap<>();
map.put("test",new Date());
System.out.println(new Date());
JSONObject jsonObject = JSONObject.parseObject(JSON.toJSONString(map,
SerializerFeature.DisableCircularReferenceDetect,
SerializerFeature.WriteDateUseDateFormat));
System.out.println(jsonObject);
}
}
结果
Mon Feb 25 14:21:54 CST 2019
{"test":"2019-02-25 14:21:54"}
设置JsonObject的默认时间格式
JSONObject.DEFFAULT_DATE_FORMAT="yyyy-MM-dd";
public class JsonTest {
public static void main(String[] args) {
HashMap<String, Date> map = new HashMap<>();
map.put("test",new Date());
System.out.println(new Date());
JSONObject.DEFFAULT_DATE_FORMAT="yyyy-MM-dd";
JSONObject jsonObject = JSONObject.parseObject(JSON.toJSONString(map, SerializerFeature.DisableCircularReferenceDetect, SerializerFeature.WriteDateUseDateFormat));
System.out.println(jsonObject);
}
}
结果
Mon Feb 25 14:29:54 CST 2019
{"test":"2019-02-25"}