GSON:Java内存不足错误堆空间

时间:2017-10-23 10:53:18

标签: java json string gson android

我正在尝试使用下面的代码将一个大对象转换为json格式作为字符串,我正在使用内存异常。但是我们使用的是1GB的堆大小。

gson.toJson(this);

如何在不增加堆大小的情况下使用gson流API(https://sites.google.com/site/gson/streaming)来消除此错误?

 Caused by: java.lang.OutOfMemoryError: Java heap space
        at java.util.Arrays.copyOf(Arrays.java:2367)
        at java.lang.AbstractStringBuilder.expandCapacity(AbstractStringBuilder.java:130)
        at java.lang.AbstractStringBuilder.ensureCapacityInternal(AbstractStringBuilder.java:114)
        at java.lang.AbstractStringBuilder.append(AbstractStringBuilder.java:415)
        at java.lang.StringBuffer.append(StringBuffer.java:237)
        at java.io.StringWriter.write(StringWriter.java:112)
        at com.google.gson.stream.JsonWriter.string(JsonWriter.java:576)
        at com.google.gson.stream.JsonWriter.writeDeferredName(JsonWriter.java:402)
        at com.google.gson.stream.JsonWriter.value(JsonWriter.java:417)
        at com.google.gson.internal.bind.TypeAdapters$16.write(TypeAdapters.java:426)
        at com.google.gson.internal.bind.TypeAdapters$16.write(TypeAdapters.java:410)
        at com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.write(TypeAdapterRuntimeTypeWrapper.java:68)
        at com.google.gson.internal.bind.MapTypeAdapterFactory$Adapter.write(MapTypeAdapterFactory.java:208)
        at com.google.gson.internal.bind.MapTypeAdapterFactory$Adapter.write(MapTypeAdapterFactory.java:145)
        at com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.write(TypeAdapterRuntimeTypeWrapper.java:68)
        at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.write(CollectionTypeAdapterFactory.java:97)
        at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.write(CollectionTypeAdapterFactory.java:61)
        at com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.write(TypeAdapterRuntimeTypeWrapper.java:68)
        at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.write(ReflectiveTypeAdapterFactory.java:112)
        at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.write(ReflectiveTypeAdapterFactory.java:239)
        at com.google.gson.Gson.toJson(Gson.java:661)
        at com.google.gson.Gson.toJson(Gson.java:640)
        at com.google.gson.Gson.toJson(Gson.java:595)
        at com.google.gson.Gson.toJson(Gson.java:575)

1 个答案:

答案 0 :(得分:1)

您可以使用流媒体方法读取大型Json文件,而无需将整个内容加载到内存中。

即使Gson也支持Streaming:https://google.github.io/gson/apidocs/com/google/gson/stream/JsonReader.html

另外:JAVA - Best approach to parse huge (extra large) JSON file