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

Categories

0 votes
158 views
in Technique[技术] by (71.8m points)

java - Stream JSON output in Spring MVC

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

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

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...