简体   繁体   中英

Simple Spring Boot POST Not Working

I have written a very simple Spring Boot GET and POST example. The GET works fine. The POST for some reason is not getting the json object. It just has nulls or zeros. Here is the rest controller code,

@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;

}

The GET /status works fine. The POST /updatebattery returns the json string but all elements of the json strings are null and the floats are zero. Here is my postman code.

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
}

This is the sent postman data,

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

This is the Postman returned result. The printf also returns a null.

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

Any idea why this simple spring boot POST program is not working?

By default, Jackson (the JSON framework used by Spring) is case sensitive, meaning that if you have a property called manufacturerId in your class, then you can only use a key called "manufacturerId" in your JSON. Jackson will not attempt to use the property if you have the key "ManufacturerId" in your JSON.

The same applies to your other properties as well. The easiest way to solve this is to make sure to match the properties in JSON to their class variant, like this:

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

However, Jackson can also be configured to be case insensitive. To do that add the following to application.properties :

spring.jackson.mapper.accept_case_insensitive_properties=true

try send json with name in lowercase. If it not solve problem check send json w/o manufacturerId (if it enum)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM