【问题标题】:Android Out of Memory parsing base64 string fromJSONAndroid Out of Memory 解析 base64 字符串 fromJSON
【发布时间】:2015-06-06 00:40:20
【问题描述】:

解析大型 JSON 字符串时出现内存不足错误。

我见过几个使用 GSON 流式传输大型 JSON 文档的示例,但我的问题是我的 JSON 文档没有成百上千个可以有效标记化的“行”。相反,它包含一个带有大约 15MB 数据的 base64 节点,例如

{
    "id":"somefile",
    "base64":"super long base64 string...."
}

如何将此 JSON 文档中的单个 base64 字符串解析为文件并保存到文件系统而不会耗尽内存?使用 StringBuilder 将 base64 节点解析为字符串是导致当前 OOM 错误的原因。例如

...
InputStream is = con.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
    sb.append(line); //out of memory
}
reader.close();
//parse the response into a POJO
MyFileClass f = new Gson().fromJson(sb.toString(), MyFileClass.class);

【问题讨论】:

    标签: android json base64 out-of-memory gson


    【解决方案1】:

    看来我找到了解决方案。在使用 GSON 之前,似乎不需要将 JSON 解析为字符串。您可以将InputStream 直接传递给 GSON,如下例所示(与问题中的代码相比):

    InputStream is = con.getInputStream();
    BufferedReader buff_reader = new BufferedReader(new InputStreamReader(is));
    //use GSON to create a POJO directly from the input stream
    MyType instance = new Gson().fromJson(buff_reader, MyType.class);
    

    我不完全确定是否需要使用 BufferedReader,因为 fromJSON 方法将直接接受 InputStreamReader,但这似乎是个好主意。

    【讨论】:

    • 这是要走的路!我认为您不需要 BufferedReader。我通常只是在里面扔一个 InputStreamReader。
    • 在哪里解密输入流和解析器之间的数据
    【解决方案2】:

    我不建议你通过json下载大文件。但如果你真的想要这个,你应该在 AndroidManifest.xml 中的应用程序标签上添加以下属性:

    <application 
        android:largeHeap="true">
        . . .
    </application>
    

    【讨论】:

      猜你喜欢
      • 2023-03-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多