Spring MVC中的流JSON输出 [英] Stream JSON output in Spring MVC

查看:344
本文介绍了Spring MVC中的流JSON输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用程序是使用Spring boot(1.3.3.RELEASE)和spring mvc,spring data jpa hibernate构建的。 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如下:

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

这篇关于Spring MVC中的流JSON输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆