我正在使用Spring实现一个RESTful Web服务。其中一个端点接受JSON字符串作为请求体,我希望将其Map到POJO。然而,目前似乎传入的JSON字符串没有Map到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注解,而且需要在实际的方法实现中有。一旦我有了它,问题就解决了。
6条答案
按热度按时间pgky5nke1#
所以结果是,请求体的值没有被传入,因为我不仅需要在接口中有@RequestBody注解,而且需要在实际的方法实现中有。一旦我有了它,问题就解决了。
s1ag04yj2#
你可以用很多方法来做,在这里我将用下面不同的方法来做-
NOTE:
请求数据应为{“customerInfo”:{“firstname”:“xyz”,“lastname”:“XYZ”}}1st way
我们可以将上面的数据绑定到Map,如下所示字符串
2nd way
我们可以直接将其绑定到pojostep 1
创建dto类UserInfo.java
型
step 1.
创建另一个dto类CustomerInfo.java
型
step 3
将请求体数据绑定到pojo型
希望对你有所帮助。谢谢
t3irkdon3#
这是可怕的格式,但这应该为Jackson配置工作。
字符串
另外,正如在评论中提到的,你的JSON对于你的对象是错误的。
型
这似乎是正确的JSON为您的对象。
jfgube3f4#
样本数据:
字符串
对于以上数据,此Spring控制器方法为我工作:
型
xggvc2p65#
我有一个类似的问题,问题是没有将DTO中的@JsonProperty添加到字段中。
字符串
avwztpqn6#
从默认构造函数中删除这两条语句并尝试