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

pom:

  1. <dependency>
  2. <groupId>com.alibaba</groupId>
  3. <artifactId>fastjson</artifactId>
  4. <version>1.2.28</version>
  5. </dependency>

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

  1. JSONObject zhangsan = new JSONObject();
  2. try {
  3. //添加
  4. zhangsan.put("name", "张三");
  5. zhangsan.put("age", 18.4);
  6. zhangsan.put("birthday", "1900-20-03");
  7. zhangsan.put("majar", new String[] {"哈哈","嘿嘿"});
  8. zhangsan.put("null", null);
  9. zhangsan.put("house", false);
  10. System.out.println(zhangsan.toString());
  11. } catch (JSONException e) {
  12. e.printStackTrace();
  13. }

2.通过hashMap数据结构生成

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

3.通过实体生成

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

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

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

5.list对象转listJson

  1. ArrayList<Student> studentLsit = new ArrayList<>();
  2. Student student1 = new Student();
  3. student1.setId(1);
  4. student1.setAge("20");
  5. student1.setName("asdasdasd");
  6. studentLsit.add(student1);
  7. Student student2 = new Student();
  8. student2.setId(2);
  9. student2.setAge("20");
  10. student2.setName("aaaa:;aaa");
  11. studentLsit.add(student2);
  12. //list转json字符串
  13. String string = JSON.toJSON(studentLsit).toString();
  14. System.out.println(string);
  15. //json字符串转listJson格式
  16. JSONArray jsonArray = JSONObject.parseArray(string);
  17. System.out.println(jsonArray);

6.JSON 字符串转换为 Java 对象

  1. @Test
  2. public void whenJson_thanConvertToObjectCorrect() {
  3. Person person = new Person(20, "John", "Doe", new Date());
  4. String jsonObject = JSON.toJSONString(person);
  5. Person newPerson = JSON.parseObject(jsonObject, Person.class);
  6. assertEquals(newPerson.getAge(), 0); // 如果我们设置系列化为 false
  7. assertEquals(newPerson.getFullName(), listOfPersons.get(0).getFullName());
  8. }

原文链接:https://blog.csdn.net/u012448904/article/details/84292821