您的位置:首页 > 移动开发 > Objective-C

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

2018-01-14 15:20 666 查看
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")=厦门市
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  json java