map与json的转换

使用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"}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容