Spring MVC 中的流式 JSON 输出

2022-01-22 00:00:00 rest java spring-mvc jackson java-stream

我的应用程序是使用带有 Spring MVC、Spring data JPA Hibernate 的 Spring Boot(1.3.3.RELEASE) 构建的.MySql 是数据库,Jackson 是 JSON 序列化程序.在 Java 8 上.

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.

我想在我的控制器方法中返回一个庞大的数据集.我不想检索所有数据然后传递到 Jackson 序列化程序,而是想返回如下对象流:

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

我的 DAO 如下所示:

my DAO is like below:

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

但是,Jackson 正在序列化流对象而不是流的内容.下面的实际输出:

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

{"parallel" : false}

如何指示 Jackson 序列化内容而不是流对象?

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

推荐答案

感谢 这个我能够解决这个问题.

Thanks to this I was able to solve the issue.

我提供了一个自定义的 httpMessageConverter,它了解如何处理流.像这样:

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

相关文章