【问题标题】:Saving a Vector of Object to SharedPreferences using Gson使用 Gson 将对象向量保存到 SharedPreferences
【发布时间】:2013-04-01 01:00:46
【问题描述】:

我正在使用 Gson 将矢量保存到 sharedpreferences

这是我的 setter 和 getter,但我似乎对我的 getter 有一些警告。

我的二传手没有任何警告

     Gson gson = new Gson();
     String json = gson.toJson(al);
     editor.putString("accountLabels", json);
     editor.commit();

我的 getter 警告我“类型安全:Vector 类型的表达式需要未经检查的转换才能符合 Vector”

    Gson gson = new Gson();
    String json = myPref.getString("accountLabels", "Error");
    Vector<AccountLabels> obj = gson.fromJson(json, Vector.class);
    return obj;

我不知道在 sharedpreferences 中保存对象甚至对象向量需要做多少工作,但这对我来说似乎是最好的解决方案。

【问题讨论】:

    标签: object vector sharedpreferences gson


    【解决方案1】:

    我不确定问题是什么。我猜这与解决未经检查的转换警告有关。为此,请更改

    Vector<AccountLabels> obj = gson.fromJson(json, Vector.class);
    

    Vector<AccountLabels> obj = gson.fromJson(json, new TypeToken<Vector<AccountLabels>>(){}.getType());
    

    出现警告是因为fromJson 方法返回类型Vector,但它被分配给Vector&lt;AccountLabels&gt; 类型的引用。

    (注意:自 2001 年以来(我认为)和更新的 Collections API,use of Vector is frowned upon。)

    【讨论】:

    • 是的,它与警告有关,感谢您提供的答案。这也很高兴知道。这有点令人失望,而且 Vectors 是如此便携。
    猜你喜欢
    • 2022-09-27
    • 2018-09-16
    • 1970-01-01
    • 1970-01-01
    • 2017-12-28
    • 2019-05-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多