string转jsonarray有双引号 Java把string转json格式的办法( 二 )

3.对象转字符串先准备一个Map和一个List
private HashMap<String, String> map1 = new HashMap<String, String>();private List<String> list1 = new ArrayList<>();private List<User> list2 = new ArrayList<>();使用JSONObject.toJSONString()方法来将对象转换为json字符串
@Testpublic void test1(){map1.put("apple","新鲜的苹果"); //向集合中添加对象map1.put("computer","配置优良的计算机");map1.put("book","堆积成山的图书");System.out.println(map1);//map对象转json字符串String s = JSONObject.toJSONString(map1);System.out.println(s);//java对象转json字符串String s1 = JSONObject.toJSONString(new User("tom", 18, "男"));System.out.println(s1);}转换数组也是一样:
@Testpublic void test2(){Collections.addAll(list1,"tom","18","男");System.out.println(list1);//ArrayList转json字符串String s = JSONObject.toJSONString(list1);System.out.println(s);//java对象的ArrayList转json字符串Collections.addAll(list2,new User("tom",18,"男"),new User("lily",16,"女"));System.out.println(JSONObject.toJSONString(list2));}