How to POST a JSON payload to a @RequestParam in Spring MVC
You can do this by registering a Converter
from String
to your parameter type using an auto-wired ObjectMapper
:
import org.springframework.core.convert.converter.Converter;
@Component
public class PersonConverter implements Converter<String, Person> {
private final ObjectMapper objectMapper;
public PersonConverter (ObjectMapper objectMapper) {
this.objectMapper = objectMapper;
}
@Override
public Person convert(String source) {
try {
return objectMapper.readValue(source, Person.class);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
Yes,is possible to send both params and body with a post method: Example server side:
@RequestMapping(value ="test", method = RequestMethod.POST)
@ResponseStatus(HttpStatus.OK)
@ResponseBody
public Person updatePerson(@RequestParam("arg1") String arg1,
@RequestParam("arg2") String arg2,
@RequestBody Person input) throws IOException {
System.out.println(arg1);
System.out.println(arg2);
input.setName("NewName");
return input;
}
and on your client:
curl -H "Content-Type:application/json; charset=utf-8"
-X POST
'http://localhost:8080/smartface/api/email/test?arg1=ffdfa&arg2=test2'
-d '{"name":"me","lastName":"me last"}'
Enjoy