json知识点总结(二)–JSONObject详解

json知识点总结(二)–JSONObject详解JSONObject只是一种数据结构,可以理解为JSON格式的数据结构(key-value 结构),可以使用put方法给json对象添加元素。JSONObject可以很方便的转换成字符串,也可以很方便的把其他对象转换成JSONObject对象。JSONObject就是对HashMap

大家好,欢迎来到IT知识分享网。json知识点总结(二)--JSONObject详解"

JSONObject只是一种数据结构,可以理解为JSON格式的数据结构(key-value 结构),可以使用put方法给json对象添加元素。JSONObject可以很方便的转换成字符串,也可以很方便的把其他对象转换成JSONObject对象。

 

JSONObject就是对 HashMap 的一层封装

 

pom:

 <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.28</version>
        </dependency>

1.通过原生生成json数据格式。

JSONObject zhangsan = new JSONObject();
        try {
            //添加
            zhangsan.put("name", "张三");
            zhangsan.put("age", 18.4);
            zhangsan.put("birthday", "1900-20-03");
            zhangsan.put("majar", new String[] {"哈哈","嘿嘿"});
            zhangsan.put("null", null);
            zhangsan.put("house", false);
            System.out.println(zhangsan.toString());
        } catch (JSONException e) {
            e.printStackTrace();
        }

2.通过hashMap数据结构生成

 HashMap<String, Object> zhangsan = new HashMap<>();
        
        zhangsan.put("name", "张三");
        zhangsan.put("age", 18.4);
        zhangsan.put("birthday", "1900-20-03");
        zhangsan.put("majar", new String[] {"哈哈","嘿嘿"});
        zhangsan.put("null", null);
        zhangsan.put("house", false);
        System.out.println(new JSONObject(zhangsan).toString());

3.通过实体生成 

 Student student = new Student();
        student.setId(1);
        student.setAge("20");
        student.setName("张三");
        //生成json格式
        System.out.println(JSON.toJSON(student));
        //对象转成string
        String stuString = JSONObject.toJSONString(student);

4.JSON字符串转换成JSON对象

String studentString = "{\"id\":1,\"age\":2,\"name\":\"zhang\"}";
 
//JSON字符串转换成JSON对象
JSONObject jsonObject1 = JSONObject.parseObject(stuString);
 
System.out.println(jsonObject1);

5.list对象转listJson

ArrayList<Student> studentLsit = new ArrayList<>();
        Student student1 = new Student();
        student1.setId(1);
        student1.setAge("20");
        student1.setName("asdasdasd");
 
        studentLsit.add(student1);
 
        Student student2 = new Student();
        student2.setId(2);
        student2.setAge("20");
        student2.setName("aaaa:;aaa");
 
        studentLsit.add(student2);
 
        //list转json字符串
        String string = JSON.toJSON(studentLsit).toString();
        System.out.println(string);
 
        //json字符串转listJson格式
        JSONArray jsonArray = JSONObject.parseArray(string);
 
        System.out.println(jsonArray);

 

总结

JSON的用途非常广泛,格式清晰明了方便理解,且其本质是用各种不同的分隔符分隔的字符串。

免责声明:本站所有文章内容,图片,视频等均是来源于用户投稿和互联网及文摘转载整编而成,不代表本站观点,不承担相关法律责任。其著作权各归其原作者或其出版社所有。如发现本站有涉嫌抄袭侵权/违法违规的内容,侵犯到您的权益,请在线联系站长,一经查实,本站将立刻删除。 本文来自网络,若有侵权,请联系删除,如若转载,请注明出处:https://yundeesoft.com/30493.html

(0)

相关推荐

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注

关注微信