大家好呀,我是柚子,今天这篇文章介绍的是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字符串和对象相互转换,也欢迎小伙伴们提出来好的意见哦!
╭◜◝ ͡ ◜◝╮
( ˃̶͈◡˂ ̶͈ )感觉有用的话,欢迎点赞评论呀!
╰◟◞ ͜ ◟◞╯
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/119845.html