1 演示JSON-LIB小工具
2 public class Demo1 {
3 /*
4 * 当map来用
5 */
6 @Test
7 public void fun1() {
8 JSONObject map = new JSONObject();
9 map.put("name", "zhangSan");
10 map.put("age", 23);
11 map.put("sex", "male");
12
13 String s = map.toString();
14 System.out.println(s);
15 }
16
17 /*
18 * 当你已经有一个Person对象时,可以把Person转换成JSONObject对象
19 */
20 @Test
21 public void fun2() {
22 Person p = new Person("liSi", 32, "female");
23 // 把对象转换成JSONObject类型
24 JSONObject map = JSONObject.fromObject(p);
25 System.out.println(map.toString());
26 }
27
28 /**
29 * JSONArray
30 */
31 @Test
32 public void fun3() {
33 Person p1 = new Person("zhangSan", 23, "male");
34 Person p2 = new Person("liSi", 32, "female");
35
36 JSONArray list = new JSONArray();
37 list.add(p1);
38 list.add(p2);
39
40 System.out.println(list.toString());
41 }
42
43 /**
44 * 原来就有一个List,我们需要把List转换成JSONArray
45 */
46 @Test
47 public void fun4() {
48 Person p1 = new Person("zhangSan", 23, "male");
49 Person p2 = new Person("liSi", 32, "female");
50 List<Person> list = new ArrayList<Person>();
51 list.add(p1);
52 list.add(p2);
53
54
55 System.out.println(JSONArray.fromObject(list).toString());
56 }