举例
假如现在有一个实体类如下所示:
@Data
pubilc class StudentVo {
private String studentName;
private Long studentAge;
}
一、json字符串转对象
1.1.单个对象
代码如下(示例):
String jsonStr = "{\"studentName\":\"小明\",\"studentAge\":18}";
JSONArray jsonArray = JSON.parseArray(jsonStr);
StudentVo studentVo = (StudentVo) JSONObject.parseArray(jsonArray.toJSONString(), StudentVo.class);
1.2.多个对象
对象A和对象B
代码如下(示例):
String jsonStr = "[{\"studentName\":\"小明\",\"studentAge\":18},{\"studentName\":\"小红\",\"studentAge\":18}]";
JSONArray jsonArray = JSON.parseArray(jsonStr);
List<StudentVo> studentList = JSONObject.parseArray(jsonArray.toJSONString(), StudentVo.class)
1.3:key为studentList,list里包含对象A和对象B
代码如下(示例):
String studentStr = "{\"studentList\":[{\"studentName\":\"小明\",\"studentAge\":18},{\"studentName\":\"小红\",\"studentAge\":18}]}";
JSONObject studentJson = JSON.parseObject(studentStr);
JSONArray studentArray = studentJson.getJSONArray("studentList");
//第一种解析方式:直接解析为对象list
List<StudentVo> studentsList = JSONObject.parseArray(studentArray.toJSONString(), StudentVo.class);
//第二种解析方式:如果需要对每个对象进行操作时,也可用第二种解析方式
for (int i = 0; i < studentArray.size(); i++) {
JSONObject student = studentArray.getJSONObject(i);
StudentVo studentVo = new StudentVo();
studentVo.setStudentName(student.getString("studentName"));
studentVo.setStudentAge(student.getString("studentAge"));
}
二、对象转json字符串
2.1 JSONObject.toJSONString(Object o)
String jsonObjectStr = JSONObject.toJSONString(studentList);
2.2 JSON.toJSONString(Object o)
String jsonObjectStr = JSON.toJSONString(studentList);