JSONObject和JSONArray的使用 以及JSONObject put,accumulate,element的区别

来源:互联网 发布:时光知味 编辑:程序博客网 时间:2024/06/13 15:53


                     

分类: web前端技术 912人阅读 评论(1)收藏 举报
JSONJava

     JSONObject是java用来处理json对象的,在java中如果用到json需要引入json包。可以到这里下载

     下面代码是JSONObject、JSONArray的简单使用,以及以及JSONObject put,accumulate,element的区别

 public static void main(String[] arg){
        
        JSONObject jsonAddr = new JSONObject();
        jsonAddr.put("city", "厦门市");
        jsonAddr.put("street", "博物馆");
        
        JSONObject json = new JSONObject();
        json.put("user", "wzj");//增加key值
        json.put("age", 12);
        json.put("addr", jsonAddr); //增加一个对象到该key下,嵌套json
        json.put("tel", "1865010");
        json.accumulate("tel", "1516003");//积累这个value到该key下,如果key存在,则该key的值为数组
        json.put("age", 20);//如果该key已经存在则覆盖原来的值
        json.put("lover", "secret");
        json.element("lover", "secret2");//这个看文档是说,如果值原来存在的话会调用accumulate,但发现这里其实没有调用accumulate?? 不知道是怎么回事?
        
        JSONArray jsonArray = new JSONArray();
        jsonArray.add(0,"person1");
        jsonArray.add(1,"person2");
        
        json.put("friend", jsonArray);//增加一个数组
        
        System.out.println("json="+json);
        System.out.println("json.getString(\"user\")="+json.getString("user"));
        System.out.println("json.getJSONArray(\"friend\").get(0)="+json.getJSONArray("friend").get(0));
        System.out.println("json.getJSONObject(\"addr\").get(\"city\")="+json.getJSONObject("addr").get("city"));
    }

输出:

json={"user":"wzj","age":20,"addr":{"city":"厦门市","street":"博物馆"},"tel":["1865010","1516003"],"lover":"secret2","friend":["person1","person2"]}
json.getString("user")=wzj
json.getJSONArray("friend").get(0)=person1
json.getJSONObject("addr").get("city")=厦门市

1 1