我正在尝试使用 spring 框架设置我的第一个 REST Web 服务。在考虑前端之前,我想首先在 Controller 中设置请求映射,并且我尝试使用 Postman 来测试它。
我正在使用 postman ,设置为 POST、raw、application/JSON,然后是以下内容:
{"attendanceList" : {
"Jane Doe": "PRESENT",
"John MacDonald": "PRESENT",
"Fred Flinstone": "ABSENT"},
"date":"2017-06-01"}
在我的 Controller 中,我有以下内容:
@RequestMapping(value = "/post", method = RequestMethod.POST, produces = {MediaType.APPLICATION_JSON_VALUE })
@ResponseBody
public void setAttendence(@RequestBody Map<String, Attendence> attendenceList, String date) {
//Implementation code
}
但是,当我向服务器发送上述 post 请求时,我得到了一张大小为 4 的 map :
"attendanceList" -> ABSENT (the default value)
"Jane Doe" -> PRESENT
"John MacDonald" -> PRESENT
"Fred Flinstone" -> ABSENT
我的字符串日期= null
为什么这没有按照我想要的方式工作?我做错了什么?
最佳答案
您告诉 Spring 请求正文(即整个 JSON)应解析为 Map<String, Attendence>
。 JSON 显然不是这样的映射。
它应该映射到一个类,例如
public class Input {
Map<String, Attendence> attendanceList;
LocalDate date;
// ...
}
当然,还有 String date
Spring 忽略的参数应该被删除。
关于java - 从 JSON 解析 Map 和 String 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44359448/