Stream JSON output in Spring MVC

后端 未结 4 1750
粉色の甜心
粉色の甜心 2020-12-08 12:19

My application is built using Spring Boot(1.3.3.RELEASE) with Spring MVC, Spring data JPA Hibernate. MySql is the database and Jackson is the JSON serializer. On java 8.

相关标签:
4条回答
  • 2020-12-08 12:28

    Thanks to this I was able to solve the issue.

    I had provide a custom httpMessageConverter that understands how to handle streams. Like so:

    @Bean
    public MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter() {
        MappingJackson2HttpMessageConverter jsonConverter = new MappingJackson2HttpMessageConverter();
        ObjectMapper objectMapper =jsonConverter.getObjectMapper();
        SimpleModule module = new SimpleModule("Stream");
        module.addSerializer(Stream.class, 
            new JsonSerializer<Stream>() {
                @Override
                public void serialize(Stream value, JsonGenerator gen, SerializerProvider serializers)
                throws IOException, JsonProcessingException {
                     serializers.findValueSerializer(Iterator.class, null)
                    .serialize(value.iterator(), gen, serializers);
                }
        });
     
        objectMapper.registerModule(module);
        jsonConverter.setObjectMapper(objectMapper);
        return jsonConverter;
    }
    
    0 讨论(0)
  • 2020-12-08 12:33

    There is a proposed solution at https://github.com/FasterXML/jackson-modules-java8/issues/3 which may be the better way to go.

    I'll not paste the code in here, as it may get updated in that issue.

    So far, I've not found any issues with that proposed code which I've added in with other modules such as the Jdk8Module for Optional as

    jacksonObjectMapper.registerModule(new StreamModule());
    
    0 讨论(0)
  • 2020-12-08 12:47

    Return Iterable<Candidate> from your controller

    Stream converts to an iterator by Iterable<X> iterable = stream::iterator;

    @RequestMapping(value = "/candidates/all", method = RequestMethod.GET)
    public Iterable<Candidate> getAllCandidates(){
        ...
    
            return candidateDao.findAllByCustomQueryAndStream()::iterator;
    
    0 讨论(0)
  • 2020-12-08 12:54

    I found that this way of adding support for streams broke the nice output of LocalDate / LocalDateTime, ended up doing it like this:

    @Bean
    public Module customModule() {
        SimpleModule module = new SimpleModule("Stream");
        module.addSerializer(Stream.class, new JsonSerializer<Stream>() {
    
            @Override
            public void serialize(Stream value, JsonGenerator gen, SerializerProvider serializers)
                    throws IOException, JsonProcessingException {
                serializers.findValueSerializer(Iterator.class, null)
                        .serialize(value.iterator(), gen, serializers);
    
            }
        });
        return module;
    }
    
    0 讨论(0)
提交回复
热议问题