【发布时间】:2016-12-21 22:56:45
【问题描述】:
我正在使用 Spring 来实现 RESTful Web 服务。其中一个端点将 JSON 字符串作为请求正文,我希望将其映射到 POJO。但是,现在看来传入的 JSON 字符串不是映射到 POJO 的属性。
这是@RestController 接口
@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”)
有人知道为什么我没有得到预期的结果吗?
修复
原来,请求体的值并没有传入,因为我不仅需要在我的接口中,而且在实际的方法实现中都需要有@RequestBody注解。有了这个,问题就解决了。
【问题讨论】:
-
如果你把那个 json 扁平化怎么办:
{"firstname":"xyz","lastname":"XYZ"} -
嗨@mszymborski,我试过了,但也没有用。使用了默认构造函数。
-
尝试在
@RequestMapping中使用consumes属性,而不是使用headers。 -
问题出在 Jackson 之外,然后 - 原始 ObjectMapper 在扁平化版本中工作得很好。
-
嗨@11thdimension,也试过了。没有帮助。
标签: java json spring spring-mvc jackson