Spring Boot REST 用于读取 JSON 数组有效负载



我有这个PostMapping方法

@PostMapping("/offreStage/{id}/users")
public ResponseEntity<?> addAuthorizedStudents(@PathVariable Long id,
@RequestBody Map<String, String> students) {
return service.addAuthorizedStudentsToOffer(id, students);
}

我使用以下 JSON 有效负载来发出我的发布请求:

[
{
"value": 15,
"label": "student2@gmail.com"
},
{
"value": 14,
"label": "student21@gmail.com"
}
]

这将返回以下内容:

"消息": "JSON 解析错误: 无法反序列化 的实例java.util.LinkedHashMap出START_ARRAY令牌;嵌套异常 is com.fasterxml.jackson.databind.exc.MismatchedInputException: 不能 从START_ARRAY中反序列化java.util.LinkedHashMap实例 token 在 [源: (PushbackInputStream(; 行: 1, 列: 1]",

发送的正文与函数中的正文不匹配。

更准确地说,这是您的地图:

{
"value": 15,
"label": "student2@gmail.com"
}

你需要一个地图列表,所以它不起作用。所以应该是这个:List<Map<String, String>>在函数中。 或者更好的是,使用集合(见这篇文章(。

由于您发送 JSON 的方式,它不起作用。在您的示例中,您实际上是以 JSON 形式发送一个地图数组,并期望 Spring 将其转换为地图。在JS中,将结构转换为单个映射,或者可以使用后端中的对象相应地映射json中的数据,如下所示:

[
{
"value": 15,
"label": "student2@gmail.com"
},
{
"value": 14,
"label": "student21@gmail.com"
}
]

然后你可以像这样使用你的控制器:

@PostMapping("/offreStage/{id}/users")
public ResponseEntity<?> addAuthorizedStudents(@PathVariable Long id,
@RequestBody List<ObjectClass> students) {
return service.addAuthorizedStudentsToOffer(id, students);
}

您的对象类可能如下所示:

public class ObjectClass {
String value;
String label;
//getters and setters
}

Map 用于键值对,您有键值对列表。

Map<String, String>更改为List<Map<String, String>>

最新更新