我正在使用 Spring 来实现 RESTful Web 服务。其中一个端点将 JSON 字符串作为请求正文,我希望将其映射到 POJO。但是,现在看来传入的 JSON 字符串不是映射到 POJO 的属性。
这是@RestController 接口(interface)
@RequestMapping(value="/send", headers="Accept=application/json", method=RequestMethod.POST)
public void sendEmails(@RequestBody CustomerInfo customerInfo);
数据模型
public class CustomerInfo {
private String firstname;
private String lastname;
public CustomerInfo() {
this.firstname = "first";
this.lastname = "last";
}
public CustomerInfo(String firstname, String lastname)
{
this.firstname = firstname;
this.lastname = lastname;
}
public String getFirstname(){
return firstname;
}
public void setFirstname(String firstname){
this.firstname = firstname;
}
public String getLastname(){
return lastname;
}
public void getLastname(String lastname){
this.lastname = lastname;
}
}
最后是我的 POST 请求:
{"CustomerInfo":{"firstname":"xyz","lastname":"XYZ"}}
Content-Type 指定为 application/json
但是,当我打印出对象值时,会打印出默认值(“first”和“last”),而不是我传入的值(“xyz”和“XYZ”)
有人知道为什么我没有得到预期的结果吗?
修复
原来,请求体的值并没有传入,因为我不仅需要在我的接口(interface)中,而且在实际的方法实现中都需要有@RequestBody注解。有了这个,问题就解决了。
最佳答案
原来,请求体的值并没有传入,因为我不仅需要在我的接口(interface)中,而且在实际的方法实现中都需要有@RequestBody注解。有了这个,问题就解决了。
关于java - Spring JSON 请求正文未映射到 Java POJO,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38960117/