簡體   English   中英

如何在 spring 引導中將 JSON hasmasp 綁定到 @RequestBody

[英]How to bind JSON hasmasp to the @RequestBody in spring boot

我想綁定這個 JSON 結構{ "male": { "id": "0001", "name": "Emma", "pet": "dog" }, "female": { "id": "0001", "name": "Cilia", "pet": "cat" } }到 java HashMap 數據結構使用 spring 引導。 但是,spring 引導無法綁定它,但如果我收到 json 作為字符串並將其手動綁定到 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) {
    ...
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM