gpt4 book ai didi

java - 如何在 Spring Boot 中将 JSON HashMap 绑定(bind)到 @RequestBody

转载 作者:行者123 更新时间:2023-12-02 09:21:26 25 4
gpt4 key购买 nike

我想绑定(bind)这个JSON结构

{
"male": {
"id": "0001",
"name": "Emma",
"pet": "dog"
},
"female": {
"id": "0001",
"name": "Cilia",
"pet": "cat"
}
}

使用spring boot @RequestBody注解来实现java HashMap数据结构。但是,Spring Boot 无法绑定(bind)它,但是如果我接收 json 作为字符串并将其手动绑定(bind)到 HashMap 它将成功。这是 HashMap

public class Tickets {

private HashMap<String, PeopleType> peopleTypes = new HashMap();
}
public class PeopleType {

private String id;

private String name;

private String pet;
}

这是 Controller

@PostMapping("/url")
public ResponseEntity bookTickets(@RequestBody Tickets tickets, HttpSession session) {
...
}

为了简洁起见,我删除了所有 Getter 和 Setter

最佳答案

试试这个:

@PostMapping("/url")
public ResponseEntity bookTickets(@RequestBody Map<String, PeopleType> peopleTypes, HttpSession session) {
Tickets tickets = new Tickets();
tickets.setPeopleTypes(peopleTypes);
...
}

或者试试这个:

public class Tickets {
private Map<String, PeopleType> peopleTypes = new HashMap<>();

@JsonAnySetter
public void addPeopleType(String type, PeopleType peopleType) {
peopleTypes.put(type, peopleType);
}
}
@PostMapping("/url")
public ResponseEntity bookTickets(@RequestBody Tickets tickets, HttpSession session) {
...
}

关于java - 如何在 Spring Boot 中将 JSON HashMap 绑定(bind)到 @RequestBody,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58669243/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com