简单的Spring Boot POST不起作用

时间:2016-06-23 22:35:38

标签: java spring-boot

我写了一个非常简单的Spring Boot GET和POST示例。 GET工作正常。 POST由于某种原因没有得到json对象。它只有零或零。这是其余的控制器代码,

@RestController
public class HttpWebServiceController {

    @RequestMapping(value = "/status", method = RequestMethod.GET)
    @ResponseBody
    public String status() throws Exception {

        // Build Service Count String
        ++ServiceCount;
        ServerResponse = "\nSecure HTTPS WebService -- ServiceCount = ";
        ServerResponse += ServiceCount +"\n\n";

        return ServerResponse;

    }

    @RequestMapping(value = "/batteryupdate", method = RequestMethod.POST)
    @ResponseBody
    public ResponseEntity<BatteryData> update(@RequestBody BatteryData
        batterydata) {

        System.out.printf("Manufacturer: %s\n",
           batterydata.getManufacturerId());
        return new ResponseEntity<BatteryData>(batterydata, HttpStatus.OK);
    }

    String ServerResponse;
    int ServiceCount = 0;

}

GET /状态正常。 POST / updatebattery返回json字符串,但json字符串的所有元素都为null,浮点数为零。这是我的邮递员代码。

POST /batteryupdate HTTP/1.1
Host: localhost:8080
Content-Type: application/json
Cache-Control: no-cache
Postman-Token: 31c74432-9d32-e7a9-0446-242a24677d2b

{
    "ManufacturerId":"Hyster",
    "Voltage": 48.76,
    "Current": 18.27
}

这是发送的邮递员数据,

{
    "ManufacturerId":"Hyster",
    "Voltage": 48.76,
    "Current": 18.27
}

这是Postman返回的结果。 printf也返回null。

{
   "current": 0,
   "manufacturerId": null,
   "voltage": 0
}

知道为什么这个简单的弹簧启动POST程序无效吗?

2 个答案:

答案 0 :(得分:3)

默认情况下,Jackson(Spring使用的JSON框架)区分大小写,这意味着如果您的类中有一个名为manufacturerId的属性,那么您只能使用名为"manufacturerId"的键。你的JSON。如果您的JSON中有密钥"ManufacturerId",Jackson将不会尝试使用该属性。

这同样适用于您的其他属性。解决此问题的最简单方法是确保将JSON中的属性与其类变体匹配,如下所示:

{
  "manufacturerId": "Hyster",
  "voltage": 48.76,
  "current": 18.27
}

但是,Jackson也可以配置为不区分大小写。为此,请将以下内容添加到 application.properties

spring.jackson.mapper.accept_case_insensitive_properties=true

答案 1 :(得分:2)

尝试使用小写的名称发送json。如果没有解决问题,请发送json w / o manufacturerId(如果它枚举)

{
   "current": 0,
   "manufacturerId": "Hyster",
   "voltage": 0
}