json lib应用示例

来源:互联网 发布:mes软件开发 编辑:程序博客网 时间:2024/05/19 06:19

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");//truejo.containsValue(90);//truejo.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"$trueja = 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);











0 0
原创粉丝点击