java - Android:保存/加载 gson.JsonObjects 的 ArrayList?

标签 java android serialization

我有以下 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/

相关文章:

c# - XmlIgnore 不起作用

java - 我应该升级到 CGLIB 3.0 吗?

java - JFrame 和 JPanel 的背景颜色不同

java - 如何在不提供 -storepass 的情况下使用 jarsign 对 jar 进行签名?

android - 我可以在 Android Studio 中测试响应式网站吗?如何?

安卓 : Failed writing handshake bytes (-1 of 14): Broken pipe

java - 无法加载 groovy 类

java - 使用场景生成器在 JavaFX 中创建按钮数组

javascript - React-Native TouchableNativeFeedback.Ripple 不起作用

java - 使用 FasterXML Jackson 进行奇怪的 JSON 序列化