Languages
[Edit]
EN

Spring MVC - JSON payload in @RequestParam

1 points
Created by:
Zachariah
328
@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);
            }
        } );
    }
}

 

Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join