JSON详解以及可以把javabean转换成json串的json-lib应用
JSON
1. json是什么
它是js提供的一种数据交换格式!
2. json的语法
{}:是对象!
属性名必须使用双引号括起来!单引不行!!!
属性值:null,数值,字符串,数组:使用[]括起来,boolean值:true和false
3. 应用json
var person = {"name":"zhangSan", "age":18, "sex":"male"};
4. json与xml比较
可读性:XML胜出
解析难度:JSON本身就是JS对象(主场作战),所以简单很多
流行度:XML已经流行好多年,但在AJAX领域,JSON更受欢迎。
json-lib
1. 是什么?
它可以把javabean转换成json串
2. jar包
json-lib的核心jar包有:
json-lib.jar
json-lib的依赖jar包有:
commons-lang.jar
commons-beanutils.jar
commons-logging.jar
commons-collections.jar
ezmorph.jar
3. 核心类
JSONObject --> Map
toString();
JSONObject map = JSONObject.fromObject(person):把对象转换成JSONObject对象
JSONArray --> List
toString()
JSONArray jsonArray = JSONObject.fromObject(list):把list转换成JSONArray对象
应用案例:
1 import java.util.ArrayList; 2 import java.util.List; 3 import net.sf.json.JSONArray; 4 import net.sf.json.JSONObject; 5 import org.junit.Test; 6 /** 7 * 演示JSON-LIB小工具 8 */ 9 public class Demo1 { 10 //当map来用 11 @Test 12 public void fun1() { 13 JSONObject map = new JSONObject(); 14 map.put("name", "zhangSan"); 15 map.put("age", 23); 16 map.put("sex", "male"); 17 String s = map.toString(); 18 System.out.println(s); 19 //输出:{"name":"zhangSan","age":23,"sex":"male"} 20 } 21 //当你已经有一个Person对象时,可以把Person转换成JSONObject对象 22 @Test 23 public void fun2() { 24 Person p = new Person("liSi", 32, "female"); 25 // 把对象转换成JSONObject类型 26 JSONObject map = JSONObject.fromObject(p); 27 System.out.println(map); 28 //输出:{"age":32,"name":"liSi","sex":"female"} 29 } 30 //JSONArray 31 @Test 32 public void fun3() { 33 Person p1 = new Person("zhangSan", 23, "male"); 34 Person p2 = new Person("liSi", 32, "female"); 35 JSONArray list = new JSONArray(); 36 list.add(p1); 37 list.add(p2); 38 System.out.println(list.toString()); 39 //输出:[{"age":23,"name":"zhangSan","sex":"male"},{"age":32,"name":"liSi","sex":"female"}] 40 } 41 //原来就有一个List,我们需要把List转换成JSONArray 42 @Test 43 public void fun4() { 44 Person p1 = new Person("zhangSan", 23, "male"); 45 Person p2 = new Person("liSi", 32, "female"); 46 List<Person> list = new ArrayList<Person>(); 47 list.add(p1); 48 list.add(p2); 49 System.out.println(JSONArray.fromObject(list).toString()); 50 //输出:[{"age":23,"name":"zhangSan","sex":"male"},{"age":32,"name":"liSi","sex":"female"}] 51 } 52 }
1 2 public class Person { 3 private String name; 4 private int age; 5 private String sex; 6 public String getName() { 7 return name; 8 } 9 public void setName(String name) { 10 this.name = name; 11 } 12 public int getAge() { 13 return age; 14 } 15 public void setAge(int age) { 16 this.age = age; 17 } 18 public String getSex() { 19 return sex; 20 } 21 public void setSex(String sex) { 22 this.sex = sex; 23 } 24 public Person() { 25 super(); 26 // TODO Auto-generated constructor stub 27 } 28 public Person(String name, int age, String sex) { 29 super(); 30 this.name = name; 31 this.age = age; 32 this.sex = sex; 33 } 34 @Override 35 public String toString() { 36 return "Person [name=" + name + ", age=" + age + ", sex=" + sex + "]"; 37 } 38 39 40 }