我得到
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");
}
关于java - 通过Gson将对象转换为Json时出现OutOfMemory异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46446212/