小编典典

@RequestBody获取空值

spring-boot

我创建了一个简单的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将空值打印为PolicyNumber的值。

请帮助我解决此问题。

我在请求正文中传递的JSON是

{
    "PolicyNumber": "123",
    "Type": "Test",
    "Tenture": "10",
    "SDate": "10-July-2016",
    "HName": "Test User",
    "Age": "10"
}

我什Content-Type至打算application/json去邮递员


阅读 1228

收藏
2020-05-30

共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对象的值。

2020-05-30