json之list参数传给springboot,4点内容
1.参考文章https://blog.csdn.net/qq_44865979/article/details/118091997
2.错误提示:JSON parse error: Cannot deserialize value of type java.util.ArrayList<实体类>
from Object value (token JsonToken.START_OBJECT
)
json对象转换成Java对象时,发生错误。可能的原因是json数据的写法出错了。
3.json数据中的属性对应的是java实体类的属性,而不是参数名字。也就是参数名不应该出现在json数据中。
例如:
User对象包含username,userage,userpwd 3个属性
1.public ResponseBean insertUser(@RequestBody User newUser)
json是{"username":"...","userage":"...","userpwd":"..."}
2.public ResponseBean insertUser(@RequestBody List<User> userlList)
json是[
{"username":"...","userage":"...","userpwd":"..."},
{"username":"...","userage":"...","userpwd":"..."},
...
]
而不是{
"UserlList":[
{"username":"...","userage":"...","userpwd":"..."},
{"username":"...","userage":"...","userpwd":"..."},
...
]
}
Scloolclass对象包含classId,className,list<User> userlList 3个属性
3.public ResponseBean insertScloolclass(@RequestBody Scloolclass sc)
json是{
"classId":"...",
"className":"...",
"userlList":[
{"username":"...","userage":"...","userpwd":"..."},
{"username":"...","userage":"...","userpwd":"..."},
,...
]
}
4.如果不知道json数据的写法时,可以先在后台向前台输出json数据,然后通过观察,发现json数据的写法。
例如
@PostMapping(value = "/insertSchedule",produces = "application/json;charset=UTF-8")
//不知道List<Schedule_detail> detailList参数的json格式。
public ResponseBean insertSchedule(@RequestBody List<Schedule_detail> detailList){
for (Schedule_detail sd:detailList) {
System.out.println(sd);
}
return new ResponseBean(200,"success",detailList);
}
@PostMapping(value = "/insertSchedule",produces = "application/json;charset=UTF-8")
// 后台输出List<Schedule_detail> detailList参数的json格式
public ResponseBean insertSchedule(){
List<Schedule_detail> detailList = new ArrayList<Schedule_detail>();
Schedule_detail s1= new Schedule_detail();
s1.setSch_detail_id(1);
Schedule_detail s2= new Schedule_detail();
s1.setSch_detail_id(2);
detailList.add(s1);
detailList.add(s2);
for (Schedule_detail sd:detailList) {
System.out.println(sd);
}
return new ResponseBean(200,"success",detailList);
}
输出结果为:可以看出List<Schedule_detail> detailList参数的json格式是[{},{}…],
而不是{“detailList”:[{},{},…]}
{
"code": 200,
"msg": "success",
"data": [
{
"sch_detail_id": 1,
"course_id": null,
"course_name": null
},
{
"sch_detail_id": 2,
"course_id": null,
"course_name": null
}
]
}