Android JsonRequest 中的 Volley 字符串太大

Android Volley too big string in JsonRequest

我正在使用 volley 发送一些相当大的 Json 请求,当 Json 对象调用 toString 时,我收到一个 java.lang.OutOfMemoryError。它在 Nexus 7 2013 Android 4.4

JsonRequest request = new JsonRequest<ResponseData>(
            method,
            url,
            EntryJsonObject.toString(),
            responseListener,
            errorListener)



java.lang.OutOfMemoryError
        at java.lang.AbstractStringBuilder.enlargeBuffer(AbstractStringBuilder.java:94)
        at java.lang.AbstractStringBuilder.append0(AbstractStringBuilder.java:132)
        at java.lang.StringBuilder.append(StringBuilder.java:124)
        at org.json.JSONStringer.string(JSONStringer.java:344)
        at org.json.JSONStringer.value(JSONStringer.java:252)
        at org.json.JSONArray.writeTo(JSONArray.java:602)
        at org.json.JSONStringer.value(JSONStringer.java:233)
        at org.json.JSONObject.writeTo(JSONObject.java:672)
        at org.json.JSONObject.toString(JSONObject.java:641)
        at com.dis.project1.restclient.Api.putInput(Api.java:205)

知道如何使用所有 Json 数据构建最终字符串,这样我就不会收到 OutOfMemory。 String 大约有 40 MBytes。它的结构有点复杂,有 3 个 Json 数组和几个对象。

您尝试过压缩字符串吗?

伪代码:

byte[] compressedBytes = compress(bigJsonString);
String base64String    = Base64.encode(compressedBytes );
[...]
byte[] origCompressedBytes  = Base64.decode(base64String);

How can I easily compress and decompress Strings to/from byte arrays?


你也可以试试Json Streaming

Most applications should use only the object model API. JSON streaming is useful in just a few situations:

  • When it is impossible or undesirable to load the entire object model into memory. This is most relevant on mobile platforms where memory is limited.
  • When it is necessary to read or write a document before it is completely available.

只需在您的应用程序中添加 android:largeHeap="true" 行 AndroidMenifest.xml。可能对你有帮助。

喜欢:

<application
        android:name=""
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        **android:largeHeap="true"**
         ...
    </application>