0

I have a standard Spring 4 MVC application. I have REST endpoints that take the ResponseBody json and maps to my Java objects. This is working great.

But now I have a need to get the raw JSON, as I do not have a Java object to map it to. My endpoint looks like this:

@RequestMapping(value="", method = RequestMethod.POST) 
@ResponseBody
public Object createObject(@RequestBody JsonObject objectJson) {

When I POST json to this endpoint I get an empty JSON string. The objectJson is not NULL, but when I debug like this:

System.out.println(objectJson.toString());

I get: {}

when I change the method signature to:

public Object createObject(@RequestBody String objectJson) {

I get a 400 "The request sent by the client was syntactically incorrect"

How do I get the JSON being sent in, either as a String that I can parse manually, or the JsonObject and I can use?

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
mmaceachran
  • 3,178
  • 7
  • 53
  • 102

1 Answers1

-2

In order to receive a JSON object using @RequestBody, you will need to define a POJO class. Suppose your raw JSON looks like

{"id":"123", "name":"John"}

The POJO will look like

public class User {
    private String id;
    private String name;

    ...
    // setters and getters
}

Your Controller method will be

@RequestMapping(value="", method = RequestMethod.POST) 
@ResponseBody
public Object createObject(@RequestBody User user) {
    String id = user.getId();
    String name = user.getName();
    ...
}
Dino Tw
  • 3,167
  • 4
  • 34
  • 48
  • How does this explain why `toString()` returns `{}` or the 400 bad request? Assuming they are using Gson's `JsonObject` and a `GsonHttpMessageConverter`, this should work out of the box. – Sotirios Delimanolis Oct 03 '16 at 17:39
  • I never used `@RequestBody` for JsonObject type, it might work, but I am not sure why toString() is empty. For 400 bad request, that's because a JSON payload is expected, but its type is String. – Dino Tw Oct 03 '16 at 17:45
  • With `String`, Jackson, by default, should use a `StringHttpMessageConverter` which just takes the request content as text and passes it to your handler method as that `String` argument. – Sotirios Delimanolis Oct 03 '16 at 17:46