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对象
应用案例:
import java.util.ArrayList; import java.util.List; import net.sf.json.JSONArray; import net.sf.json.JSONObject; import org.junit.Test; /** * 演示JSON-LIB小工具 */ public class Demo1 { //当map来用 @Test public void fun1() { JSONObject map = new JSONObject(); map.put("name", "zhangSan"); map.put("age", 23); map.put("sex", "male"); String s = map.toString(); System.out.println(s); //输出:{"name":"zhangSan","age":23,"sex":"male"} } //当你已经有一个Person对象时,可以把Person转换成JSONObject对象 @Test public void fun2() { Person p = new Person("liSi", 32, "female"); // 把对象转换成JSONObject类型 JSONObject map = JSONObject.fromObject(p); System.out.println(map); //输出:{"age":32,"name":"liSi","sex":"female"} } //JSONArray @Test public void fun3() { Person p1 = new Person("zhangSan", 23, "male"); Person p2 = new Person("liSi", 32, "female"); JSONArray list = new JSONArray(); list.add(p1); list.add(p2); System.out.println(list.toString()); //输出:[{"age":23,"name":"zhangSan","sex":"male"},{"age":32,"name":"liSi","sex":"female"}] } //原来就有一个List,我们需要把List转换成JSONArray @Test public void fun4() { Person p1 = new Person("zhangSan", 23, "male"); Person p2 = new Person("liSi", 32, "female"); List<Person> list = new ArrayList<Person>(); list.add(p1); list.add(p2); System.out.println(JSONArray.fromObject(list).toString()); //输出:[{"age":23,"name":"zhangSan","sex":"male"},{"age":32,"name":"liSi","sex":"female"}] } }
public class Person { private String name; private int age; private String sex; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public Person() { super(); // TODO Auto-generated constructor stub } public Person(String name, int age, String sex) { super(); this.name = name; this.age = age; this.sex = sex; } @Override public String toString() { return "Person [name=" + name + ", age=" + age + ", sex=" + sex + "]"; } }