【发布时间】:2016-12-20 12:39:19
【问题描述】:
我创建了一个简单的 REST 服务 (POST)。但是当我从邮递员那里调用这个服务时,@RequestBody 没有收到任何值。
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
@RestController
public class Add_Policy {
@ResponseBody
@RequestMapping(value = "/Add_Policy", headers = {
"content-type=application/json" }, consumes = MediaType.APPLICATION_JSON_VALUE, method = RequestMethod.POST)
public Policy GetIPCountry( @RequestBody Policy policy) {
System.out.println("Check value: " + policy.getPolicyNumber());
return policy;
}
}
我的 java Bean 对象如下:
public class Policy {
private String PolicyNumber;
private String Type;
private String Tenture;
private String SDate;
private String HName;
private String Age;
public String getPolicyNumber() {
return PolicyNumber;
}
public void setPolicyNumber(String policyNumber) {
PolicyNumber = policyNumber;
}
public String getType() {
return Type;
}
public void setType(String type) {
Type = type;
}
public String getTenture() {
return Tenture;
}
System.out.println 正在打印一个 null 作为 PolicyNumber 的值。
请帮我解决这个问题。
我在请求正文中传递的 JSON 是
{
"PolicyNumber": "123",
"Type": "Test",
"Tenture": "10",
"SDate": "10-July-2016",
"HName": "Test User",
"Age": "10"
}
我什至在邮递员中将Content-Type 设置为application/json
【问题讨论】:
-
将
@ResponseBody应用于方法的输出而不是方法本身。如果您期望 JSON 值,还包括produces标头值。 -
即使我将响应设为 void,请求中的值也是相同的 null
-
policy本身不为空,你确定它包含policyNumber吗? -
Policy对象中的所有值都恢复为 null。我添加了一个tostring()方法policybean 并检查了这个。 -
请您向我们展示您的 json 请求吗?
标签: spring spring-boot spring-restcontroller