@RequestBody 正在获取空值

新手上路,请多包涵

我创建了一个简单的 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

原文由 Geek 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 471
1 个回答

尝试将 JSON 中属性的第一个字符设置为小写。例如。

 {
    "policyNumber": "123",
    "type": "Test",
    "tenture": "10",
    "sDate": "10-July-2016",
    "hName": "Test User",
    "age": "10"
}

基本上,Spring 使用 getter 和 setter 来设置 bean 对象的属性。它获取 JSON 对象的属性,将其与同名的 setter 匹配。例如,要设置policyNumber 属性,它会尝试在您的bean 类中找到一个名为setpolicyNumber() 的setter,并使用它来设置您的bean 对象的值。

原文由 AmanSinghal 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题