把一个对象 转为JSON格式的方法

 List list = new ArrayList<>();
        list.add("y12");
        list.add("w23");
        list.add("r2");
        list.add("y23");
        String str="haha:lala";
        Project project =new Project();
        project.setL0name("China");
        project.setL1name("Guangdong");
        project.setL2name("Dongguan");
        project.setEditors(list);
        Map map=new LinkedHashMap<>();
        map.put("pro", project);

//转为JSON对象的对象
        System.out.println(JSON.toJSON(map));

// 转为json对象的字符串
        System.out.println(JSON.toJSONString(map));
        System.out.println(JSON.toJSONString(JSON.toJSON(map)));

//就是一个字符串
        System.out.println(JSON.toJSONString(JSON.toJSONString(map)));

输出结果:

{"pro":{"l1name":"Guangdong","l0name":"China","l2name":"Dongguan","editors":["y12","w23","r2","y23"]}}
{"pro":{"editors":["y12","w23","r2","y23"],"l0name":"China","l1name":"Guangdong","l2name":"Dongguan"}}
{"pro":{"l1name":"Guangdong","l0name":"China","l2name":"Dongguan","editors":["y12","w23","r2","y23"]}}
"{\"pro\":{\"editors\":[\"y12\",\"w23\",\"r2\",\"y23\"],\"l0name\":\"China\",\"l1name\":\"Guangdong\",\"l2name\":\"Dongguan\"}}"

 

参考:

"haah"+JSON.toJSONString(JSON.toJSONString(project.getEditors()))
     (java.lang.String) haah"[\"张三\",\"李四\"]"
     
"haha"+JSON.toJSONString(project.getViewers())
     (java.lang.String) haha["四"]
             
"haha"+JSON.toJSON(project.getScenes())

     (java.lang.String) haha["测试"]     


 

 

你可能感兴趣的:(JSON)