JSONObject 这个对象可以看作是一个Map
两个构造方法:
JSONObject jo = new JSONObject();
JSONObject jo = JSONObject.fromObject(这里需要一个map对象或javabean对象);
转化成json串: String json = jo.toString();
JSONArray 这个对象可以看做是一个List
两个构造方法:
JSONArray ja = JSONArray.fromObject();
JSONArray ja = JSONArray.fromObject(这里需要一个collection集合对象);
转化成json串: String json = ja.toString();
案例分析:
--->实体类 Person.java
要求:①必须public修饰②有getter和setter方法
1 package json; 2 3 public class Person { 4 private String name; 5 private int age; 6 private String sex; 7 8 public String getName() { 9 return name; 10 } 11 public void setName(String name) { 12 this.name = name; 13 } 14 public int getAge() { 15 return age; 16 } 17 public void setAge(int age) { 18 this.age = age; 19 } 20 public String getSex() { 21 return sex; 22 } 23 public void setSex(String sex) { 24 this.sex = sex; 25 } 26 public Person() {} 27 public Person(String name, int age, String sex) { 28 super(); 29 this.name = name; 30 this.age = age; 31 this.sex = sex; 32 } 33 34 }
--->测试类 TestJson.java
1 package json; 2 3 import java.util.ArrayList; 4 import java.util.HashMap; 5 import java.util.List; 6 import java.util.Map; 7 8 import net.sf.json.JSONArray; 9 import net.sf.json.JSONObject; 10 11 import org.junit.Test; 12 13 public class TestJson { 14 15 @Test 16 public void fun(){ 17 JSONObject jo = new JSONObject();//创建map对象 18 jo.put("name", "张三"); 19 jo.put("age", 23); 20 jo.put("sex", "male"); 21 String json = jo.toString(); 22 //{"name":"张三","age":23,"sex":"male"} 23 System.out.println(json); 24 } 25 @Test 26 public void fun1(){ 27 Person p1 = new Person("李四",24,"male"); 28 Person p2 = new Person("王五",25,"female"); 29 Map<String,Person> map = new HashMap<String,Person>(); 30 map.put("1", p1); 31 map.put("2", p2); 32 33 JSONObject mapJson = JSONObject.fromObject(map);//创建mapJson 34 35 //{"2":{"age":25,"name":"王五","sex":"female"},"1":{"age":24,"name":"李四","sex":"male"}} 36 System.out.println(mapJson.toString()); 37 38 39 Person person = new Person("LiSi", 18, "female"); 40 JSONObject beanJson = JSONObject.fromObject(person);//创建beanJson 41 42 //{"age":18,"name":"LiSi","sex":"female"} 43 System.out.println(beanJson.toString()); 44 45 } 46 47 @Test 48 public void fun2(){ 49 Person p1 = new Person("李四",24,"male"); 50 Person p2 = new Person("王五",25,"female"); 51 List<Person> list = new ArrayList<Person>(); 52 list.add(p1); 53 list.add(p2); 54 JSONArray ja = JSONArray.fromObject(list);//从list中创建对象 55 String json = ja.toString(); 56 //[{"age":24,"name":"李四","sex":"male"},{"age":25,"name":"王五","sex":"female"}] 57 System.out.println(json); 58 59 JSONArray jsonList = new JSONArray(); 60 jsonList.add(p1); 61 jsonList.add(p2); 62 //[{"age":24,"name":"李四","sex":"male"},{"age":25,"name":"王五","sex":"female"}] 63 System.out.println(jsonList.toString()); 64 } 65 66 }
时间: 2024-10-24 00:58:10