1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > json字符串和对象的相互转换

json字符串和对象的相互转换

时间:2020-05-02 17:59:26

相关推荐

json字符串和对象的相互转换

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

文章目录

举例一、json字符串转对象1.单个对象2.多个对象二、对象转json字符串1.第一种方式2.第二种方式总结

举例

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

@Datapubilc 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");//第一种解析方式:直接解析为对象listList<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字符串和对象相互转换,也欢迎小伙伴们提出来好的意见哦!

╭◜◝ ͡ ◜◝╮

( ˃̶͈◡˂ ̶͈ )感觉有用的话,欢迎点赞评论呀!

╰◟◞ ͜ ◟◞╯

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。