json lib应用示例

1. JSONObject对象

    直接用例子说话。

JSONObject jo = new JSONObject();
jo.put("age",9);//jo.toString() = {"age":90}
jo.put("name","paul");//jo.toString() = {"name":"paul","age":90}
jo.accumulate("name", "1");//jo.toString() = {"name":["paul","1"],"age":90}
jo.accumulate("sex", "male");//jo.toString() = {"name":["paul","1"],"age":90,"sex":"male"}
Map<String, String> map = new HashMap<String, String>();
map.put("key1", "v1");
map.put("key2", "v2");
jo.accumulateAll(map);//jo.toString() = {"name":["paul","1"],"age":90,"sex":"male","key2":"v2","key1":"v1"}
jo.containsKey("name");//true
jo.containsValue(90);//true
jo.discard("name");//{"age":90,"sex":"male","key2":"v2","key1":"v1"}
jo.element("sex", "female");//{"age":90,"sex":"female","key2":"v2","key1":"v1"}--网上说如果key是存在的就调用accumulate方法,实际发现不是。未发现element与put方法的差异
Set set = jo.entrySet();//set中的元素{age=90,sex=female,key2=v2,key1=v1}
jo.clear();//jo.toString() = {}

    JSONObject.fromObject(Object object);   //该静态方法用参数对象构造一个JSONObject对象

    其它实例方法:

    getString(String key)  getInt(String key)  getBoolean(String key)...

    get(String key)----返回对象类型

    keys()  values()  keySet()  remove(String key)  remove(Object key)

2.JSONArray对象

JSONArray ja = new JSONArray();
ja.add("hello");//["hello"]
ja.add("world");//["hello","world"]
ja.addAll(Arrays.asList(new String[]{"heo","wod"}));//["hello","world","heo","wod"]
ja.add(1,"first");//["hello","first","world","heo","wod"]
ja.discard(1);//["hello","world","heo","wod"]
ja.discard("heo");//["hello","world","wod"]
ja.element(true);//["hello","world","wod",true]
ja.set(1, 100);//["hello",100,"wod",true]
String str = ja.join("$");//str="hello"$100$"wod"$true
ja = JSONArray.fromObject(new int[]{1,5});//[1,5]

    其它实例方法:

    get(int index)  getString(int index)  getLong(int index)

    contains(Object o)  containsAll(Collection collection)

    remove(Object o)  removeAll(Collection collection)

    JSONArray.toArray(JSONArray ja)//该方法返回Object对象可以强制转换为数组类型

3.json字符串转化为包含复杂对象集合的bean

public class A{
  private B list<B> list;
  //省略getter、setter
}
public class B{
  private int age;
  private String name;
  //省略getter、setter
}

JSONObject jo = JSONObject.fromObject(stringJsonObject);
Map<String,Class> classMap = new HashMap<String, Class>();
classMap.put("list",B.class);
A a = (A) JSONObject.toBean(jo,A.class,classMap);








 



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值