apache提供的json-lib小工具,它可以方便的使用Java语言来创建JSON字符串。也可以把JavaBean转换成JSON字符串。
在json-lib中只有两个核心类:
1, JSONObject;
2,JSONArray;
JSONObject类本身是一个Map
1
2 3 4 5 6 7 |
JSONObject jo =
new JSONObject();
jo.put( "name", "zhangSan"); jo.put( "age", "18"); jo.put( "sex", "male"); System.out.println(jo.toString()); 结果: { "name": "zhangSan", "age": "18", "sex": "male"} |
1
2 3 4 |
Person person =
new Person(
"liSi",
18,
"female");
JSONObject jo = JSONObject.fromObject(person); System.out.println(jo.toString()); |
1
2 3 4 5 6 7 8 |
Map map =
new HashMap();
map.put( "name", "wangWu"); map.put( "age", "81"); map.put( "sex", "male"); JSONObject jo = JSONObject.fromObject(map); System.out.println(jo.toString()); |
1
2 3 4 5 |
String xml =
"<person><name>zhaoLiu</name><age>59</age><sex>female</sex></person>";
XMLSerializer serial = new XMLSerializer(); JSONObject jo = (JSONObject)serial.read(xml); System.out.println(jo.toString()); |
JSONArray本身是一个List
1
2 3 4 5 6 7 8 |
JSONArray ja =
new JSONArray();
Person p1 = new Person( "zhangSan", 18, "male"); Person p2 = new Person( "liSi", 23, "female"); ja.add(p1); ja.add(p2); System.out.println(ja.toString()); |
1
2 3 4 5 6 7 8 9 10 |
Person p1 =
new Person(
"zhangSan",
18,
"male");
Person p2 = new Person( "liSi", 23, "female"); List<Person> list = new ArrayList<Person>(); list.add(p1); list.add(p2); JSONArray ja = JSONArray.fromObject(list); System.out.println(ja.toString()); |
1
2 3 4 5 6 7 8 |
Person p1 =
new Person(
"zhangSan",
18,
"male");
Person p2 = new Person( "liSi", 23, "female"); Person[] persons = {p1, p2}; JSONArray ja = JSONArray.fromObject(persons); System.out.println(ja.toString()); |
服务器发送过来JSON字符串后,客户端需要对其进行解析。这时客户端需要使用eval()方法对JSON字符串进行执行!但要注意,eval()方法在执行JSON时,必须把JSON字符串使用一对圆括号括起来。
1
2 3 4 |
var json =
"{\"name\
":\"zhangSan\
", \"age\
":\"18\
", \"sex\
":\"male\
"}";
var person = eval( "(" + json + ")"); alert(person.name + ", " + person.age + ", " + person.sex); |