-1

I use java 11 and spring. I try to send two objects via post to the controller, but I get an error.

Here the controller:

@PostMapping("/new_info/buildingData")
public Map<String, List<Buildings>> getBuildingData(
        @RequestBody Boolean isIncluded,
        @RequestBody BuildingData buildingData
        ) {
    Map<String, List<Buildings>> results = new HashMap<>();
    results.put("results", buildingService.findBuildingDataByInfoId(BuildingData, isGood));
    return results;
}

Here the data that I send via swagger:

{
  "isIncluded": true,
  "buildingData": {
    "id": "1232165",
    "name": "Tir44",
    "description": "West side road 45",
  }
}

When I try to hit the function above I get this error:

 c.p.s.utility.ExceptionHandlerAdvice : <=== Exception: JSON parse error: Cannot deserialize instance of `java.lang.Boolean` out of START_OBJECT token; nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of `java.lang.Boolean` out of START_OBJECT token

Any idea why I get the error and how to fix it?

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
Michael
  • 13,950
  • 57
  • 145
  • 288
  • Does this answer your question? [Cannot deserialize instance of \`java.lang.String\` out of START\_OBJECT token](https://stackoverflow.com/questions/54062469/cannot-deserialize-instance-of-java-lang-string-out-of-start-object-token) – darkmnemic May 26 '21 at 19:42
  • 1
    `@RequestBody` is used to indicate that the request body should be parsed and converted to the annotated parameter's type. Since parameters are visited in order, Spring MVC will attempt to deserialize the request body into a `Boolean`. There's no known conversion from a JSON object to a `Boolean`. You probably meant to use a POJO type with those two fields. – Sotirios Delimanolis May 26 '21 at 20:06

2 Answers2

2

You can use path variable for your boolean parameter isIncluded and buildingData in requestBody as below with this you don't need two requestbody, passing buildingData alone in requestbody is sufficient

@RequestMapping(value = "/new_info/buildingData/{isIncluded}", method = RequestMethod.POST)
    public Map<String, List<Buildings>> getBuildingData(@RequestBody BuildingData buildingData, @PathVariable boolean isIncluded) {
...
}
sanjeevRm
  • 1,541
  • 2
  • 13
  • 24
1

Since there can be only one body you have to create a wrapper for your input:

class BuildingDataDTO {
    Boolean isIncluded;
    BuildingData buildingData;
    // getters/setters omitted
}

and use it as an argument

@PostMapping("/new_info/buildingData")
public Map<String, List<Buildings>> getBuildingData(
        @RequestBody BuildingDataDTO dto
) {
   Boolean isIncluded = dto.getIsIncluded();
   BuildingData buildingData = dto.getBuildingData();
   ...
}
Nikolai Shevchenko
  • 7,083
  • 8
  • 33
  • 42