EN
Spring MVC - JSON payload in @RequestParam
1
points
@Configuration
@EnableWebMvc
public class WebAppConfig implements WebMvcConfigurer {
@Override
public void addFormatters(FormatterRegistry registry) {
ObjectMapper mapper = new ObjectMapper();
/**
* Allows to send json array of strings as @RequestParam.
* Example:
* var array=["Java"];
* is encoded by encodeURIComponent and send as:
* http://localhost:8080/path/?array=%5B%22Java%22%5D
* and received in controller as:
* @RequestParam(value = "array") String[] array
* that array[0] items is "Java" string
*/
registry.addConverter(String.class, String[].class, source -> {
try {
return mapper.readValue(source, String[].class);
} catch (Exception e) {
throw new RuntimeException(e);
}
} );
}
}