Search code examples
javaspringwebclientmime-typesspring-webflux

how to configure spring-5 “webclient (with jetty connector)” webflux with mediatype "application/x-ndjson"


I am trying to access rest end point which will return response with mediatype "application/x-ndjson" header. How to consume this endpoint with spring 5 Webclient? Will it work if I set media type to "application/stream+json" in Spring 5 WebClient ?


Solution

  • You should be able to create your own Jackson2JsonDecoder with all the media types you'd like to support (including this specific mediatype).

    Something like:

    Jackson2JsonDecoder jsonDecoder = new Jackson2JsonDecoder(Jackson2ObjectMapperBuilder.json().build(), 
        new MimeType("application", "json"), new MimeType("application", "x-ndjson"));
    
    

    And then configure this decoder directly in the WebClient while building it:

    WebClient webClient = WebClient.builder().codecs(codecs -> codecs.defaultCodecs().jackson2JsonDecoder(jsonDecoder)).build();
    

    If you're using Spring Boot, you can achieve all that with:

    @Configuration
    public class JsonConfiguration {
    
      @Bean
      public CodecCustomizer ndJsonCustomizer(ObjectMapper objectMapper) {
        Jackson2JsonDecoder jsonDecoder = new Jackson2JsonDecoder(objectMapper, 
            new MimeType("application", "json"), new MimeType("application", "x-ndjson"));
        return codecs -> codecs.defaultCodecs().jackson2JsonDecoder(jsonDecoder);
      }
    
    }
    

    In the future, you might not need to do that since the Spring Framework team is considering ndjson support out-of-the-box to replace stream+json.