我有以下 Cart
类,其中 mCartItems
的数组列表为 gson.JsonObjects。
public class Cart {
private ArrayList<JsonObject> mCartItems;
private Context mContext;
...
}
// Save cart singleton to disk
public void saveToDisk(){
try {
FileOutputStream fos = mContext.openFileOutput(FILE_NAME, Context.MODE_PRIVATE);
ObjectOutputStream os = new ObjectOutputStream(fos);
os.writeObject(mCartItems);
os.close();
Log.v(LOG_TAG, "Saving cart to disk");
} catch (IOException io){
mContext.deleteFile(FILE_NAME);
Log.v(LOG_TAG, "Error saving cart to disk", io);
}
当我保存 cartItems 时,收到错误 java.io.NotSerializedException: com.google.gson.JsonObject
。如何在不继承 JsonObject 的情况下将购物车商品列表存储在文件中?
最佳答案
根据the API , toString()
在JsonObject
上给你一个String
这是对象的有效 Json 表示形式。
一个String
是可序列化的,当您从磁盘读回它时,您可以将其解析回 JsonObject
.
将转换步骤添加到您的 saveToDisk()
应该相当简单(以及您拥有的任何 readFromDisk()
方法)更改您的 ArrayList<JsonObject>
到ArrayList<String>
然后再回来。
关于java - Android:保存/加载 gson.JsonObjects 的 ArrayList?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25212344/