大家好呀,我是柚子,今天这篇文章介绍的是json字符串和对象的相互转换~


举例

假如现在有一个实体类如下所示:

@Data
pubilc class StudentVo {
    private String studentName;
	private Long studentAge;
}

提示:以下是本篇文章正文内容,下面案例可供参考

一、json字符串转对象

1.单个对象

代码如下(示例):

String jsonStr = "{\"studentName\":\"小明\",\"studentAge\":18}";
JSONArray jsonArray = JSON.parseArray(jsonStr);
StudentVo studentVo = (StudentVo) JSONObject.parseArray(jsonArray.toJSONString(), StudentVo.class);

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)

第二种形式: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字符串

1.第一种方式

String jsonObjectStr = JSONObject.toJSONString(studentList);

2.第二种方式

String jsonObjectStr = JSON.toJSONString(studentList);

总结

以上就是今天要讲的内容,本文简单介绍了json字符串和对象相互转换,也欢迎小伙伴们提出来好的意见哦!


╭◜◝ ͡ ◜◝╮
( ˃̶͈◡˂ ̶͈ )感觉有用的话,欢迎点赞评论呀!
╰◟◞ ͜ ◟◞╯

Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐