Stream JSON output in Spring MVC(Spring MVC 中的流式 JSON 输出)
问题描述
我的应用程序是使用带有 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;
}
这篇关于Spring MVC 中的流式 JSON 输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Spring MVC 中的流式 JSON 输出
- C++ 和 Java 进程之间的共享内存 2022-01-01
- 如何使用WebFilter实现授权头检查 2022-01-01
- Spring Boot连接到使用仲裁器运行的MongoDB副本集 2022-01-01
- Safepoint+stats 日志,输出 JDK12 中没有 vmop 操作 2022-01-01
- Java包名称中单词分隔符的约定是什么? 2022-01-01
- Jersey REST 客户端:发布多部分数据 2022-01-01
- Eclipse 插件更新错误日志在哪里? 2022-01-01
- 从 finally 块返回时 Java 的奇怪行为 2022-01-01
- value & 是什么意思?0xff 在 Java 中做什么? 2022-01-01
- 将log4j 1.2配置转换为log4j 2配置 2022-01-01