I want to bind this JSON structure { "male": { "id": "0001", "name": "Emma", "pet": "dog" }, "female": { "id": "0001", "name": "Cilia", "pet": "cat" } }
to java HashMap data structure using spring boot @RequestBody annotation. However, spring boot is not able to bind it, but if i receive the json as string and bind it manually to the hashmap it will succeed. Her is the HashMap
public class Tickets {
private HashMap<String, PeopleType> peopleTypes = new HashMap();
}
public class PeopleType {
private String id;
private String name;
private String pet;
}
Here is the controller
@PostMapping("/url")
public ResponseEntity bookTickets(@RequestBody Tickets tickets, HttpSession session) {
...
}
I removed all Getters and Setters for brevity
Try this:
@PostMapping("/url")
public ResponseEntity bookTickets(@RequestBody Map<String, PeopleType> peopleTypes, HttpSession session) {
Tickets tickets = new Tickets();
tickets.setPeopleTypes(peopleTypes);
...
}
Or try this:
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) {
...
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.