【发布时间】:2016-02-21 16:13:44
【问题描述】:
我在我的应用程序中使用 Dropwizard 0.9.1,并且我有一个返回 ChunkedOuput 的 GET 方法,如 here 所述。 MediaType 应该是 APPLICATION_JSON 并且它可以工作,但结果不是有效的 JSON。
这里是示例资源:
@GET
@Path("/chunktest")
@Produces(MediaType.APPLICATION_JSON)
public class AsyncResource {
@GET
public ChunkedOutput<MyCustomObject> getChunkedResponse() {
final ChunkedOutput<MyCustomObject> output = new ChunkedOutput<MyCustomObject>(MyCustomObject.class);
new Thread() {
public void run() {
try {
MyCustomObject chunk;
while ((chunk = getNextCustomObject()) != null) {
output.write(chunk);
}
} catch (IOException e) {
// IOException thrown when writing the
// chunks of response: should be handled
} finally {
output.close();
// simplified: IOException thrown from
// this close() should be handled here...
}
}
}.start();
// the output will be probably returned even before
// a first chunk is written by the new thread
return output;
}
private MyCustomObjectgetNextCustomObject() {
// ... long running operation that returns
// next object or null
}
}
现在如果我尝试 curl 这个无效的 JSON 被返回:
HTTP/1.1 200 OK
Date: Thu, 19 Nov 2015 13:08:28 GMT
Content-Type: application/json
Vary: Accept-Encoding
Transfer-Encoding: chunked
{
"key1" : "value1a",
"key2" : "value2a"
}{
"key1" : "value1b",
"key2" : "value2b"
}{
"key1" : "value1c",
"key2" : "value2c"
}{
"key1" : "value1d",
"key2" : "value2d"
}
我也尝试使用块分隔符,但我只能修复块 JSON 之间的“,”,但我不知道如何插入开始/结束括号
{
和
}
有谁知道如何解决这个问题?
【问题讨论】:
-
难道你不能在
run()方法的开头使用output.write("["),在 finally 块中使用output.write("]")吗?这与您上面提到的分隔符相结合,会将输出转换为 JSON 数组。 -
使用带有上述内容的 messageBodyWriter 实际上是唯一的方法,我如何才能使其正常工作,但这对我来说仍然只是一种解决方法;-)
-
@MusikPolice 那将如何完成? ChunkedOutput 的类型不是 String.class...
标签: java json jersey dropwizard chunked-encoding