【问题标题】:Deal with huge JSON responses处理巨大的 JSON 响应
【发布时间】:2014-10-21 05:54:31
【问题描述】:

我认为我需要重写我的应用程序的一些模块,因为当渲染的实体数量增加时,它也会失败和错误。目前,我正在使用JacksonHttpClient。尽管我很信任杰克逊,但有些东西告诉我问题出在第二个库上。 HttpClient 可以处理大量响应吗? (例如this one 大约有 400 行)

除此之外,在我的应用中,我解析请求的方式是这样的:

public Object handle(HttpResponse response, String rootName) {
    try {
        String json = EntityUtils.toString(response.getEntity()); 
        // better "new BasicResponseHandler().handleResponse(response)" ????
        int statusCode = response.getStatusLine().getStatusCode();
        if ( statusCode >= 200 && statusCode < 300 ) {
            return createObject(json, rootName);
        }
        else{
            return null;
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

public Object createObject (String json, String rootName) {
    try {
        this.root = this.mapper.readTree(json);
        String className = Finder.findClassName(rootName);
        Class clazz = this.getObjectClass(className);
        return mapper.treeToValue(root.get(rootName), clazz);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

我如何改进这段代码,以提高响应的效率?

提前致谢!

【问题讨论】:

  • 您遇到的具体错误/异常是什么?你看过Request/Response entity streaming吗?
  • 我不记得了,但是,我需要在 Android 中使用流式传输类吗? : o

标签: java android rest jackson


【解决方案1】:

无需创建String json,因为ObjectMapper#readTree 也可以接受InputStream。例如,这会稍微高效一些:

public Object handle(HttpResponse response, String rootName) {
    try {
        int statusCode = response.getStatusLine().getStatusCode();
        if ( statusCode >= 200 && statusCode < 300 ) {
            return createObject(response.getEntity().getContent(), rootName);
        }
        else{
            return null;
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

}

public Object createObject (InputStream json, String rootName) {
    try {
        this.root = this.mapper.readTree(json);
        String className = Finder.findClassName(rootName);
        Class clazz = this.getObjectClass(className);
        return mapper.treeToValue(root.get(rootName), clazz);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

【讨论】:

  • 我在询问之前尝试过,但它给我带来了更多问题。
【解决方案2】:

我猜你可以将数据读取到一个好的旧 StringBuffer 中。类似的东西

HttpEntity httpEntity = httpResponse.getEntity();
if (httpEntity != null) {
    InputStream is = AndroidHttpClient.getUngzippedContent(httpEntity);
    br = new BufferedReader(new InputStreamReader(is));
    StringBuilder sb = new StringBuilder(8192);
    String s;
    while ((s = br.readLine()) != null) sb.append(s);
}

【讨论】:

  • 我看不出这会如何改变任何事情。
【解决方案3】:

我已经处理了 1000 多行 json 响应而没有问题,所以这应该不是问题。至于更好的方法,谷歌 GSON 很棒,它可以将您的 json 映射到您的 java 对象,而无需任何特殊的解析代码。

【讨论】:

    猜你喜欢
    • 2012-06-27
    • 2013-09-28
    • 2015-01-07
    • 2014-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多