0

I want to access the request body object of my REST endpoint, which is already deserialized.

My REST controller looks like this:

@RequestMapping(value = "car/{id}", method = RequestMethod.PUT)
public ResponseEntity updateCar(@RequestBody Car car, @PathVariable("id") String carId) {
    // My update logic, how i update the car object in database
    // with the retrieved request body. 
    // Here i want to access the raw request body e.g. the JSON string
}

Edit:

The Car POJO:

public class Car {
    private String id;
    private String name;
    private String color;
    private List<String> additions =  new ArrayList<>();

    // setters and getters
}

When i want to make a partial update, e.g a PUT request like this:

curl -X PUT \
    -H "Content-Type: application/json" \
    -d "{ \"color\" : \"Green\" }" \
    http://localhost:8080/car/1234

After the deserialization of the request body above, the additions field is an empty list although i didn't specified it. If i could access the raw json request body, then i can check whether the additions field is specified or not.

Is it possible to access the raw request body after it was deserialized?

Oni1
  • 1,445
  • 2
  • 19
  • 39
  • Not sure about your use case but why do you want to do that? – Rishikesh Dhokare Jan 29 '18 at 07:06
  • @RishikeshDhokare check my question, i updated it. – Oni1 Jan 29 '18 at 07:18
  • Ofcourse it is empty, that is what you initialize it with. – M. Deinum Jan 29 '18 at 07:34
  • @Oni1, I dont think this is a good idea to access the raw request body. I guess you can omit your list initialization, so it would be `null` if `additions` parametr wasn't specified. – Leffchik Jan 29 '18 at 07:36
  • Yes.... But in the JSON request body, i don't specify it. I want to make it possible to update partially.. Therefore i want to check e.g. if the `additions` field is really specified as an empty list in the request or is it the default value? – Oni1 Jan 29 '18 at 07:38
  • @Leffchik You're right, but atm it is not possible to change the model classes. – Oni1 Jan 29 '18 at 07:39
  • @Oni1, weird, but in that case I guess any solution would be hacky. You can get request json as string then in a first place ([like that for ex](https://stackoverflow.com/a/17891906/2653420)) and then deserialize it manually the way you want. – Leffchik Jan 29 '18 at 07:51
  • @Leffchik That's really hacky.. I wish there is nice solution from spring.. – Oni1 Jan 29 '18 at 10:24
  • have you tried @JsonDeserialize (from jackson) and create your own deserializer? That's where you can check if things are not as they should be – codebrane Jan 29 '18 at 13:51

0 Answers0