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



我有一个对象的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}, {...}]
}

如何使用Jackson生成JSON并将其流式传输到响应,而无需填充所有数据的内存?

Jackson带有一个通用的StreamSerializer。当你加入Jdk8Module时你就得到它了给你的ObjectMapper.

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

完成后,您可以序列化您的Stream<Person>很容易:

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

JSON输出如下所示:

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

相关内容

  • 没有找到相关文章

最新更新