• JSONObject/JSONArray的区别


    JSONObject/JSONArray的区别

    (1)JSONObject : java对象,用{}包裹起来
    例如:{”id”:1 , “username”:”wp”}
    (2)JSONArray : 数组或字符串[1,2,3]
    (3)特殊形式:
    {“id”:1 , “username:” :”wp” , “books” :[{“book1” : “java开发”},{ “book2” : “android开发”}]}这是JSONObject中嵌套JSONArray的形式,其中books是JSONArray的形式,books中又含有book1,book2的JSONObject的形式 获取方式:
    JSONArray array = jsonObject.getJSONArray(“books”);
    (3)写入JSONObject

            JSONObject json=new JSONObject(); 
            JSONObject json1=new JSONObject(); 
            JSONObject json2=new JSONObject(); 
            JSONArray books=new JSONArray();  
            json1.put("book1","java开发");
            json2.put("book2","android开发");
            books.put(json1);
            books.put(json2);
            json.put("id",1);
            json.put("username","wp");
            json.put("username","wp");
            json.put("books",books);
            System.out.println(json.toString());

    结果:

    {"books":[{"book1":"java开发"},{"book2":"android开发"}],"id":1,"username":"wp"}

    (4)读取json数据

            String s=json.toString();
            JSONArray array = json.getJSONArray("books");
            JSONObject a=new JSONObject(s);
            System.out.println(array);
            System.out.println(a.getInt("id"));

    结果:

    [{"book1":"java开发"},{"book2":"android开发"}]
    1

    (5)list转JSONArray( map,数组 转json与其类似)

            ArrayList<String> list=new ArrayList<String>();
            list.add("java");
            list.add("android");
            JSONArray jsonarray = JSONArray.fromObject(list);
            System.out.println(jsonarray);

    (6)Object对象转JSONObject

            User u1=new User(1,"wp1");
            User u2=new User(2,"wp2");
            ArrayList<User> list=new ArrayList<User>();
            list.add(u1);
            list.add(u2);
            JSONObject jsonobject =JSONObject.fromObject(list);
            System.out.println(jsonobject);
  • 相关阅读:
    包含min函数的栈
    量化交易系统的四个组成部分
    顺时针打印矩阵
    python正则表达式中re.M,re.S,re.I的作用
    二叉树的镜像
    树的子结构
    合并两个排序的链表
    反转链表
    命名元祖
    二叉树(二叉搜索树-AVL树-B树)
  • 原文地址:https://www.cnblogs.com/wangxiaopei/p/8551266.html
Copyright © 2020-2023  润新知