@RequestBody获取空值

Gee*_*eek 19 spring spring-boot spring-restcontroller

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

    }


}
Run Code Online (Sandbox Code Playgroud)

我的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;
    }
Run Code Online (Sandbox Code Playgroud)

System.out.println正在打印null作为PolicyNumber的值.

请帮我解决这个问题.

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

{
    "PolicyNumber": "123",
    "Type": "Test",
    "Tenture": "10",
    "SDate": "10-July-2016",
    "HName": "Test User",
    "Age": "10"
}
Run Code Online (Sandbox Code Playgroud)

我甚Content-Type至打算application/json在邮递员

小智 32

检查将导致问题的@RequestBody 导入。

应该是 --> import org.springframework.web.bind.annotation.RequestBody;

  • 是的。对我来说,重要的是来自于招摇。啊! 谢谢你的提示。 (8认同)
  • 我的问题是从 swagger 导入而不是 springframework ...... (5认同)
  • 对我来说,进口也是来自于招摇 (4认同)
  • 同样,关于大摇大摆的阻碍 (3认同)

Ama*_*hal 29

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

{
    "policyNumber": "123",
    "type": "Test",
    "tenture": "10",
    "sDate": "10-July-2016",
    "hName": "Test User",
    "age": "10"
}
Run Code Online (Sandbox Code Playgroud)

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

  • 我仍然明白这个问题。我的属性都是小写的。它获取对象,但所有空值都是这样``Task{id=0,eachingHours=null,surveillanceHours=null,proofReading=null,isActive=false,isValidated=false,candidateId=null,supervisorId=null}``` (3认同)
  • 我遇到这个问题是因为我忘记创建 getter 和 setter。 (2认同)

小智 8

如果您无权更改 JSON 格式但仍想解决此问题,请尝试 @JsonNaming(PropertyNamingStrategy.UpperCamelCaseStrategy.class) 在 DTO(示例中的策略)类之前添加注释。


小智 6

二传手会被错过。因此,对象值不会被设置。


小智 5

Java 约定要求 POJO(类的属性)中的变量名称必须是小写的第一个字符。

您的 JSON 属性中有大写字母,这就是导致失败的原因。