大约一年前,我写了一篇博客文章,展示了如何使用Jersey / Jax RS流式传输HTTP响应 ,最近我想做同样的事情,但是这次使用JSON。
一种常见的模式是获取我们的Java对象并获取该对象的JSON字符串表示形式,但这并不是最有效的内存使用方式,因为我们现在有了Java对象和一个字符串表示形式。
如果我们需要在响应中返回大量数据,则这尤其成问题。
通过编写更多代码,我们可以在部分准备就绪后立即将响应发送到客户端,而不是构建整个结果并一次性发送所有结果:
@Path("/resource")
public class MadeUpResource
{private final ObjectMapper objectMapper;public MadeUpResource() {objectMapper = new ObjectMapper();}@GET@Produces(MediaType.APPLICATION_JSON)public Response loadHierarchy(@PathParam( "pkPerson" ) String pkPerson) {final Map<Integer, String> people = new HashMap<>();people.put(1, "Michael");people.put(2, "Mark");StreamingOutput stream = new StreamingOutput() {@Overridepublic void write(OutputStream os) throws IOException, WebApplicationException{JsonGenerator jg = objectMapper.getJsonFactory().createJsonGenerator( os, JsonEncoding.UTF8 );jg.writeStartArray();for ( Map.Entry<Integer, String> person : people.entrySet() ){jg.writeStartObject();jg.writeFieldName( "id" );jg.writeString( person.getKey().toString() );jg.writeFieldName( "name" );jg.writeString( person.getValue() );jg.writeEndObject();}jg.writeEndArray();jg.flush();jg.close();}};return Response.ok().entity( stream ).type( MediaType.APPLICATION_JSON ).build() ;}
}
如果运行此输出,我们将看到:
[{"id":"1","name":"Michael"},{"id":"2","name":"Mark"}]
这是一个简单的示例,但希望可以很容易地看到如果我们想流式传输更复杂的数据时可以如何翻译它。
翻译自: https://www.javacodegeeks.com/2014/04/jerseyjax-rs-streaming-json.html