Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

I want to return a huge data set in my controller method. Instead of retrieving all the data and then passing into the Jackson serializer, I want to return a stream of objects like below:

@RequestMapping(value = "/candidates/all", method = RequestMethod.GET)
public Stream<Candidate> getAllCandidates(){
    try { 
        return candidateDao.findAllByCustomQueryAndStream();
    } catch(Exception e){
        LOG.error("Exception in getCandidates",e);
    }
    return null;
}

my DAO is like below:

@Query("select c from Candidate c")
public Stream<Candidate> findAllByCustomQueryAndStream();

However, Jackson is serializing the stream object instead of the contents of the stream. The actual output below:

{"parallel" : false}

How can I instruct Jackson to serialize the content and not the stream object?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
143 views
Welcome To Ask or Share your Answers For Others

1 Answer

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;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...