Reputation: 3567
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. Here 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
Upvotes: 1
Views: 5273
Reputation: 159106
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) {
...
}
Upvotes: 3