简体   繁体   English

如何使用 Jackson 从对象流生成 JSON 流

[英]How to generate a stream of JSON from a stream of objects with Jackson

I have a Stream of objects and an outgoing HttpServletResponse :我有一个对象Stream和一个传出的HttpServletResponse

public class Person {
    public String name;
    public Int age;
    ...
}

@RequestMapping(value = "/my/path", produces = MediaType.APPLICATION_JSON_VALUE)
    public void getPersons(HttpServletRequest request, HttpServletResponse response) {
        Stream<Person> stream = getMyStream();

        // write stream of JSON array to response: [{name: "xx", age: 00}, {...}]
    }

How to I generate JSON using Jackson and stream this to the response without filling the memory with all the data?如何使用 Jackson 生成 JSON 并将其流式传输到响应而不用所有数据填充内存?

Jackson comes with a generic StreamSerializer . Jackson 带有一个通用的StreamSerializer You get it when you add the Jdk8Module to your ObjectMapper .当您将Jdk8Module添加到ObjectMapper时,您就会得到它。

ObjectMapper objectMapper = new ObjectMapper()
        .registerModule(new Jdk8Module());

Having done that you can serialize your Stream<Person> very easily:完成后,您可以非常轻松地序列化Stream<Person>

Stream<Person> stream = getMyStream();
OutputStream out = response.getOutputStream();
objectMapper.writeValue(out, stream);

Then the JSON output will look like this:然后 JSON 输出将如下所示:

[{"name":"Alice","age":30},{"name":"Bob","age":31},{"name":"Charlie","age":32}]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM