json-lib的应用
json-lib
1. 是什么?
* 它可以把javabean转换成json串
2. jar包
* 略
3. 核心类
* JSONObject --> Map
> toString();
> JSONObject map = JSONObject.fromObject(person):把对象转换成JSONObject对象
* JSONArray --> List
> toString()
> JSONArray jsonArray = JSONObject.fromObject(list):把list转换成JSONArray对象
-------------------------------------------------------------------------------------
实例代码:
public class json1 {
@Test
//当作map来用
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);
}
@Test
//把对象转成json
public void fun2(){
Person p=new Person("zhangsan",20);
JSONObject map=JSONObject.fromObject(p);
String s=map.toString();
System.out.println(s);
}
@Test
//JSONArray
public void fun3(){
Person p1=new Person("zhangsan",20);
Person p2=new Person("lisi",22);
JSONArray list=new JSONArray();
list.add(p1);
list.add(p2);
System.out.println(list.toString());
}