假如现在有一个实体类如下所示:
@Data
pubilc class StudentVo {
private String studentName;
private Long studentAge;
}
提示:以下是本篇文章正文内容,下面案例可供参考
代码如下(示例):
String jsonStr = "{\"studentName\":\"小明\",\"studentAge\":18}";
JSONArray jsonArray = JSON.parseArray(jsonStr);
StudentVo studentVo = (StudentVo) JSONObject.parseArray(jsonArray.toJSONString(), StudentVo.class);
第一种形式:对象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"));
}
String jsonObjectStr = JSONObject.toJSONString(studentList);
String jsonObjectStr = JSON.toJSONString(studentList);
以上就是今天要讲的内容,本文简单介绍了json字符串和对象相互转换,也欢迎小伙伴们提出来好的意见哦!
╭◜◝ ͡ ◜◝╮
( ˃̶͈◡˂ ̶͈ )感觉有用的话,欢迎点赞评论呀!
╰◟◞ ͜ ◟◞╯
因篇幅问题不能全部显示,请点此查看更多更全内容
Copyright © 2019- stra.cn 版权所有 赣ICP备2024042791号-4
违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com
本站由北京市万商天勤律师事务所王兴未律师提供法律服务