【问题标题】:Android - HTTP GET Request huge size of JSON responseAndroid - HTTP GET 请求巨大的 JSON 响应
【发布时间】:2014-04-02 06:51:03
【问题描述】:

我有一个很大的 JSON 输入 (download the file) API,但我不知道如何解析这些数据。我需要:

  1. 将此数据(整个 JSON 输入)保存到文本文件或数据库。最好的方法是什么?
  2. 从文本文件或数据库中加载此数据,并从 JSON 标签“list”(第一个标签)创建 JSONArray

该解决方案应该很快并且支持 Android 2.3。你对此有什么建议?有什么想法吗?

我的代码:

        HttpClient httpClient = new DefaultHttpClient();

        HttpGet httpGet = new HttpGet(urls[0]);

        HttpResponse httpResponse;

        httpResponse = httpClient.execute(httpGet);

        HttpEntity httpEntity = httpResponse.getEntity();

            ... and what next ?...

仅供参考:

EntityUtils 抛出 OutOfMemoryException

编辑:

我尝试像这样将数据保存到文件中:

            InputStream inputStream = httpEntity.getContent();

            FileOutputStream output = new FileOutputStream(Globals.fileNews);
            int bufferSize = 1024;
            byte[] buffer = new byte[bufferSize];
            int len = 0;

            while ((len = inputStream.read(buffer)) != -1) {
                output.write(buffer, 0, len);
            }

没关系。我加载数据:

            FileInputStream fis = null;
            StringBuffer fileContent = new StringBuffer("");

            fis = new FileInputStream(Globals.fileNews);

            byte[] buffer = new byte[1024];

            while (fis.read(buffer) != -1) {
                fileContent.append(new String(buffer));
            }

但是如何将StringBuffer 转换为JSONObjectfileContent.ToString() 不理想,有时我得到OutOfMemoryException

【问题讨论】:

  • JSON 被用于动态处理。试试这个答案:link

标签: android json performance http get


【解决方案1】:

首先:处理HttpClient。 Google 不鼓励这样做:

不幸的是,Apache HTTP 客户端没有,这是众多客户端之一 我们不鼓励使用它的原因。

来源:developer.android.com

一个很好的替代品是Google Volley。您必须自己构建 JAR,但它就像魅力一样。我使用OkHttp-StackGSON requests 设置Google Volley。

在您的情况下,您将编写另一个请求,它只是将响应逐块写入 SD 卡。您之前没有缓冲字符串!还有一些逻辑可以从您编写的文件中打开一个输入流并将其提供给您的 JSON 反序列化器。 Jackson 和 GSON 能够开箱即用地处理流。

当然,一切都适用于 Android 2.3。

不要,我再说一遍,不要试图将整个序列化的东西转储到字符串或其他东西中。这几乎是 OutOfMemoryException 的保证。

【讨论】:

    猜你喜欢
    • 2014-09-01
    • 2021-08-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多