Search code examples
jsonspringgetrequestput

Spring Boot: How to add JSON Object to GET request?


I'm new to spring boot. I have a JSON Object that looks like this:

{
    id: 3,
    messageType: ["one", "two", "three"]
}

I have a class that represents the object:

public class Subscription {
    public Subscription(@JsonProperty("id") long id, @JsonProperty("messageType") List<String> messageType) {
        this.id = id;
        this.messageType = messageType;
    }
}

I have a controller with a PUT request that works perfectly:

    @RequestMapping(value=SUBSCRIBE_URI, method=RequestMethod.PUT)
    public ResponseEntity<String> updateSubscription(@RequestBody Subscription payload) throws Exception{
        ...
    }

But I can't get this working at all for the GET request. When I use @RequestParam and separate the id and messageType parameters, the messageType list has brackets in the strings (i.e. "[one]", "[two]"). When I use @RequestBody similar to the PUT request, I get 400 errors.

What is the correct way to pass this JSON data to the GET request without getting brackets in the strings?


Solution

  • You can't send JSON on the request parameter, directly. You'll need to do something like call encodeURIComponent() on the json structure you want to pass to your server and then have the argument just be a string. On the server side you need to convert the string back into your model object.