栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

[会写代码的健身爱好者成长史]之JsonObject常用方法

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

[会写代码的健身爱好者成长史]之JsonObject常用方法

    //JsonObject是key/values的形式存在
        JSonObject jsonObject = new JSonObject();

        //1、put给jsonObject添加key/values形式的数据
        jsonObject.put("name","张三");
        jsonObject.put("age","18");
        jsonObject.put("sex","男");
        //根据key获取values
        String name = jsonObject.getString("name");
        System.out.println(name);


        //2、JSONObject.parseObject(studentString)将studentString字符串转化为key/values形式的JsonObject对象
        String studentString = "{"id":1,"age":2,"name":"zhang"}";
        JSonObject jsonObject1 = JSONObject.parseObject(studentString);
        System.out.println(jsonObject1);

        //3、JSONObject对象中的value是一个JSONObject对象,即根据key获取对应的JSONObject对象
        JSonObject jsonObject2 = new JSonObject();
        jsonObject2.put("user",jsonObject);
        JSonObject user = jsonObject2.getJSonObject("user");
        System.out.println(user);

        //4、获取JSONObject中的键值对个数
        int size = jsonObject.size();
        System.out.println(size);

        //5、判断是否为空
        boolean result = jsonObject.isEmpty();
        System.out.println(result);

        //6、是否包含对应的key值,包含返回true,不包含返回false
        boolean isContainsKeyResult = jsonObject.containsKey("name");
        System.out.println(isContainsKeyResult);

        //7、是否包含对应的value值,包含返回true,不包含返回false
        boolean isContainsValueResult = jsonObject.containsValue("王五");
        System.out.println(isContainsValueResult);

        //8、remove.根据key移除JSONObject对象中的某个键值对
        jsonObject.remove("name");
        System.out.println(jsonObject);

        //9、取得JSONObject对象中key的集合
        Set keySet= jsonObject.keySet();
        for (String key : keySet) {
            System.out.print("   "+key);
        }
        System.out.println();
        
        //10、转换为json字符串
        String str1 = jsonObject.toJSonString();
        System.out.println(str1);
    }

tips:记得添加fastJson依赖

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/319279.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号