實現思路
Student(對象) 轉換成json字符串 解析成Map(對象)
Map(對象) 轉換成json字符串 解析成Student(對象)
連個主要方法
JSON.toJSONString(對象);
JSON.parseObject(jsonString,Class);
Student student = new Student();
student.setId(1);
student.setStudentName("狗蛋");
student.setScore(new BigDecimal("20.213"));
student.setBirthday(new Date());
String studentJson = JSON.toJSONString(student);
System.out.println("studentJson:" + studentJson);
Map map = JSON.parseObject(studentJson, Map.class);
System.out.println("map:" + map);
String mapJson = JSON.toJSONString(map);
Student student1 = JSON.parseObject(mapJson, Student.class);
System.out.println(student1);
打印結果
studentJson:{"birthday":1572340893369,"id":1,"score":20.213,"studentName":"狗蛋"}
map:{birthday=1572340893369, score=20.213, studentName=狗蛋, id=1}
Student{id=1, studentName='狗蛋', score=20.213, birthday=Tue Oct 29 17:21:33 CST 2019}
注意如果對象中屬性爲date類型,轉成map的時候變成了時間戳,此時需要考慮一些時間展示問題。