通过 Gson 将对象转换为 Json 时出现 OutOfMemory 异常

OutOfMemory exception when converting object to Json through Gson

我得到

java.lang.OutOfMemoryError

对于某些用户(并非总是如此),当我使用 Gson 将对象列表转换为 JSON 时。请告诉我如何解决这个问题。

@Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        if(myList != null && !myList.isEmpty()) {
            //exception at this line
            String myJson = new Gson().toJson(myList, myList.getClass());
            outState.putString(MY_LIST, myJson);
        }
        outState.putInt(NEXT_PAGE, getNextPage());
    }

myList 是我的自定义对象列表,列表大小为 400kb 到 600kb

这将取决于您的列表的大小。你为什么不使用流式传输 API https://sites.google.com/site/gson/streaming

更具体一点,比如

public String writeListToJson(List myList) throws IOException {
    ByteArrayOutputStream byteStream =new ByteArrayOutputStream();
    OutputStreamWriter outputStreamWriter=new OutputStreamWriter(byteStream ,"UTF-8");
    JsonWriter writer = new JsonWriter(outputStreamWriter);
    writer.setIndent("  ");
    writer.beginArray();
    Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().setPrettyPrinting().create();
    for (Object o : myList) {
        gson.toJson(o, o.class, writer);
    }
    writer.endArray();
    writer.close();
    return byteStream.toString("UTF-8");
}

myList is the list of my custom object and size of list is 400kb to 600kb

不要不要 将其置于保存的实例状态BundleOutOfMemoryError 只是您的担忧之一。很多时候您会因 FAILED BINDER TRANSACTION 而崩溃,因为您的应用中同时进行的所有 IPC 事务都有 1MB 的限制。

如果您正在尝试处理配置更改,请使用其他方法来保存此信息:

  • 保留片段
  • onRetainNonConfigurationInstance()
  • ViewModel 来自 Android 架构组件
  • 等等

如果您正在尝试处理进程 termination/app 重新启动,请在保存的实例状态 Bundle 中放置一个标识符,这将允许您从持久存储(数据库、纯文件)重新加载此列表等)。