Rodriguez
Rodriguez

Reputation: 165

How to pass two arguments of custom type in spring controller using request body and method PUT

Here users pass to the method normally:

@PutMapping
    @RequestMapping("/update_user")
    public String update(@RequestBody List<CustomUser>users) {
        return ......
    }   

Postman PUT request body:

    [
    {"name":"Name1"},
    {"name":"Name2"}
    ]

But here I receive an error: "Failed to resolve argument 1 of type CustomUser":

@PutMapping
    @RequestMapping("/update_user")
    public String update(@RequestBody CustomUser user1, CustomUser user2) {
        return ......
    }

Postman PUT request body:

    {
    "user1":{"name":"Name1"},
    "user2":{"name":"Name2"}
    }

What am I doing wrong?

Upvotes: 1

Views: 590

Answers (1)

lucid
lucid

Reputation: 2900

RequestBody annotated parameter is expected to hold the entire body of the request and bind to one object, so you essentially will have to go with one object only

Now, Either you can wrap them both like this

public class Payload {
    CustomUser user1;
    CustomUser user2;
    
    //getters & setters
}

and use that for RequestBody

@PostMapping
@RequestMapping("/update_user")
public String update(@RequestBody Payload users) {
    return ......
}

Or you can use a Map<String, CustomUser> for RequestBody

@PostMapping
@RequestMapping("/update_user")
public String update(@RequestBody Map<String, CustomUser> users) {
    //you can access like this
    
    CustomUser user1 = users.get("user1");
    CustomUser user2 = users.get("user2");
}

Another thing to note, you are mapping as POST request but your comment says "PUT". check that as well.

Upvotes: 1

Related Questions