有没有办法在我的API响应中流式传输Json?
通过这个例子,我理解了如何使用jackson库来读写json文件:
http://www.mkyong.com/java/jackson-streaming-api-to-read-and-write-json/
但是现在在play框架中,如何流式传输我的响应,或者换句话说,返回return ok();的API接口中的内容
发布于 2015-04-23 20:15:47
在你的控制器中,你会有一个类似于下面这行的操作:
public Result chunkedJson() {
return ok(readJsonChunks());
}在readJsonChunks方法中,您实际上创建了块:
public static Chunks<String> readJsonChunks() {
Chunks<String> chunks = new StringChunks() {
@Override
public void onReady(play.mvc.Results.Chunks.Out<String> out) {
JsonFactory jfactory = new JsonFactory();
try {
// Read from file
JsonParser jParser = jfactory.createJsonParser(new File("c:\\user.json"));
// Loop until token equal to "}"
while (jParser.nextToken() != JsonToken.END_OBJECT) {
// Write all your JSON stuff into out, e.g. with
String text = jParser.getText();
out.write(text);
}
jParser.close();
} catch (IOException e) {
out.write("Couldn't open file c:\\user.json");
} finally {
out.close();
}
}
};
return chunks;
}我从未尝试过这种特定的代码(特别是我从未使用过JsonFactory.createJsonParser -它似乎已被弃用),但我使用类似的方法将日志文件从服务器发送到客户端。
(我正在使用Play 2.2.3)
https://stackoverflow.com/questions/29802060
复制相似问题