Java 中常用的JSONobject的用法详解

2年前 (2022) 程序员胖胖胖虎阿
204 0 0

1、本文详细讲解了JSONObject的用法,文中通过示例代码介绍的非常详细。对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下

2、pom中添加的包为

<dependency>

<groupId>com.alibaba</groupId>

<artifactId>fastjson</artifactId>

<version>1.2.28</version>

</dependency>

3、通过原生生成json数据格式。

JSONObject Person = new JSONObject();
Person.put("name","小明");
Person.put("age","18");
Person.put("school","北京大学");
Person.put("local","北京");
System.out.println(Person.toJSONString());

输出结果为:

Java 中常用的JSONobject的用法详解

4、通过hashMap数据结构生成。

Map<String,Object> map = new HashMap<>();
map.put("name","yyy");
map.put("age",12);
map.put("hobby","游泳");
System.out.println(new JSONObject(map).toJSONString());

输出结果为:

Java 中常用的JSONobject的用法详解 

5、通过实体生成 

Student stu = new Student();
stu.setAge("18");
stu.setName("小红");
stu.setSchool("北京大学");
JSONObject stu_json = (JSONObject) JSON.toJSON(stu);
System.out.println(stu_json.toString());
输出结果为

Java 中常用的JSONobject的用法详解

6、JSON字符串转换成JSON对象

String studentString = "{\"id\":1,\"age\":2,\"name\":\"zhang\"}";

JSONObject jsonObject1 = JSONObject.parseObject(stuString);

  System.out.println(jsonObject1);

7、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);

 

版权声明:程序员胖胖胖虎阿 发表于 2022年9月28日 下午12:00。
转载请注明:Java 中常用的JSONobject的用法详解 | 胖虎的工具箱-编程导航

相关文章

暂无评论

暂无评论...