2016-08-13 116 views
6

我创建了一个简单的REST服务(POST)。但是当我从邮递员调用此服务@RequestBody没有收到任何值。@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-Typeapplication/json

+1

将'@ ResponseBody'应用于方法的输出而不是方法本身。如果您期待JSON值,还需要包含“产品”标头值。 – 11thdimension

+0

即使我将响应作为无效,请求中的值也是相同的null – Geek

+0

'policy'本身不为null,您确定它包含'policyNumber'吗? – 11thdimension

回答

10

尝试设置属性的第一个字符在你的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对象的值。

1

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

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