Reputation: 2750
I am developing a spring boot application and now want to post the user details into the backend.I am posting a Json data to the backend by following code:
@RestController
public class DataInsertController {
@RequestMapping(value = "data/api", consumes={MediaType.APPLICATION_JSON_VALUE},method = RequestMethod.POST)
public ResponseEntity<HostResponse> createAuthenticationToken(@RequestBody Host host ) {
System.out.println(host.getName());
return ResponseEntity.ok(new HostResponse("token"));
}
}
My Object class is like
import java.io.Serializable;
public class Host implements Serializable{
private static final long serialVersionUID = -8445943548965154778L;
private String name;
private String email;
public Host(){
super();
}
public Host(String name, String email) {
this.setName(name);
this.setEmail(email);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
I am posting the data like
{
"name": "user01",
"email":"[email protected]"
}
from my Rest Client.But data is not printed in the backend. Any help is appreciated.
Upvotes: 0
Views: 1955
Reputation: 306
If you are using Postman to send data then send data in body part instead of header as you have used @RequestBody to get the data.
This will solve your problem
Upvotes: 1
Reputation: 579
You need to annotate your class with the Jackson Annotations else it won't know which field to deserialise:
@JsonCreator
public Host((@JsonProperty("name")String name,@JsonProperty("email") String email) {
this.setName(name);
this.setEmail(email);
}
Upvotes: 1
Reputation: 970
I use so effective solution to get post body as json. you can get body as string and convert it to your obejct(Host class) by using ObjectMapper as follow :
@RestController
public class DataInsertController {
@RequestMapping(value = "data/api", consumes={MediaType.APPLICATION_JSON_VALUE},method = RequestMethod.POST)
public ResponseEntity<HostResponse> createAuthenticationToken(@RequestBody Map<String,Object> hostMap ) {
// handle json object exceptions to validate input
JSONObject jsonObject = new JSONObject(hostMap);
Host host = new ObjectMapper().readValue(jsonObject.toString() , Host.class);
System.out.println(host.getName());
return ResponseEntity.ok(new HostResponse("token"));
}
}
Upvotes: 1