2015-06-05 34 views
2

解析大型JSON字符串時發生內存不足錯誤。Android Out of Memory從JSON解析base64字符串

我見過使用GSON傳輸大型JSON文檔的幾個例子,但我的問題是我的JSON文檔沒有數百或數千個可以高效標記的'行'。而是它包含一個大約15MB數據的單個base64節點,例如

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

如何解析單個base64字符串從此JSON文檔到文件並保存到文件系統而不會耗盡內存?使用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); 

回答

-1

我不建議你通過json下載大文件。但是,如果你真的想這樣,你應該把下面的屬性,您的應用程序標籤在AndroidManifest.xml:

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

已經大堆,thx – rmirabelle

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,但它似乎是個好主意。

+0

這是要走的路!我不認爲你需要BufferedReader。我通常只是在裏面放入一個InputStreamReader。 –

+0

在哪裏解密輸入流和解析器之間的數據 –