在Dropwizard应用程序中使用ChunkedOutput和JSON的Jersey

时间:2015-11-19 13:26:53

标签: java json jersey dropwizard chunked-encoding

我在我的应用程序中使用Dropwizard 0.9.1并且我有一个GET-Method返回一个ChunkedOuput,如描述here。 MediaType应该是APPLICATION_JSON,它可以工作,但结果不是有效的JSON。

以下是Ressource示例:

@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"
}

我也尝试使用块分隔符,但是我只能修复chunk-JSON之间的“,”,但我不知道如何插入开始/结束括号

  

{

  

}

有谁知道如何解决这个问题?

2 个答案:

答案 0 :(得分:2)

一起黑客攻击:)

public class ChunkedOutputJson<T> extends ChunkedOutput<String> {
    private boolean isFirstChunk = true;
    private final JsonSerializer jsonSerializer;
    public ChunkedOutputJson(JsonSerializer jsonSerializer) {
        super(String.class);
        this.jsonSerializer = jsonSerializer;
    }
    public void writeChunk(T chunk) throws IOException {
        if (isFirstChunk) {
            super.write("[\n");
            isFirstChunk = false;
        } else {
            super.write(",\n");
        }
        super.write(jsonSerializer.toJson(chunk));
    }
    @Override
    public void close() throws IOException {
        super.write("\n]\n");
        super.close();
    }
}

原因我没有在原始ChunkedOutput中使用delimiter属性,它会在最后一个元素之后添加它,因此搞砸了json格式(如果你需要严格的话)。

答案 1 :(得分:-1)

new ChunkedOutput<MyCustomObject>(MyCustomObject.class, ",")怎么样?

第二个参数的Javadoc:

@param chunkDelimiter custom chunk delimiter string. Must not be {code null}.

(对于泽西2)