【问题标题】:How to retrieve Strings from Shared Preference using GSON?如何使用 GSON 从 Sharedpreferences 中检索字符串?
【发布时间】:2013-11-20 06:41:41
【问题描述】:

我正在保存我的

"ArrayList<Item> items = new ArrayList<Item>();" 

在 Shared Preference 中使用 GSON,下面的代码运行良好

protected static void saveItems(){
        SharedPreferences prefs = context.getSharedPreferences("prefName", Context.MODE_PRIVATE);
        Editor editor = prefs.edit();
        editor.putString("myList", new Gson().toJson(items).toString());
        editor.apply();
    }

检索

protected void retreiveItems(){
    preferences = context.getSharedPreferences("prefName",android.content.Context.MODE_PRIVATE);
    saveitems = preferences.getString("myList", "");
    Log.d("LOG", "Retreived Items : " + saveitems);
}

但检索再次给出 JSON 格式。

Retreived Items : [{"subtitle":"20 Nov 2013 12:35:19","title":"Sync Successful"},{"subtitle":"20 Nov 2013 12:35:44","title":"Sync Successful"}]

如何将每个 JSON 集提取到两个不同的字符串中,以便将其添加到我的列表视图中

items.add(new EntryItem(title, subtitle));

【问题讨论】:

  • 您应该首先检查您在首选项中输入的值。 new Gson().toJson(items).toString()->它给了你什么?
  • How can i extract each JSON set into two different strings so that i can add it into my listview. 除了将其保存为两个不同的字符串之外,最好对其进行解析并将其存储到创建 POJO 类的自定义数组列表中。

标签: android listview sharedpreferences gson


【解决方案1】:

您可以将 json 数组直接填充到 EntryItem 类对象,而不是一一获取字符串。 gson 将为您提供 EntryItem[] 数组。

例如,您的 EntryItem 类如下

public class EntryItem {

    private String subtitle;
    private String title;
       // setter getter here
}

您现在可以像这样解析 json 字符串

EntryItem[] items = gson.fromJson(reader, EntryItem[].class);

subtiltle是json格式的日期,Entry项也会给出字符串格式的日期,你可以根据自己改变格式

如果您希望 Gson 在解析期间更改您的日期格式,那么您必须执行以下操作

final GsonBuilder builder = new GsonBuilder();
        builder.registerTypeAdapter(Date.class, new JsonDeserializer<Date>() {

            final DateFormat df = new SimpleDateFormat("dd MMM yyyy hh:mm:ss");

            @Override
            public Date deserialize(final JsonElement json, final Type typeOfT,
                    final JsonDeserializationContext context)
                    throws JsonParseException {
                try {
                    System.out.println(json.getAsString());
                    return df.parse(json.getAsString());
                } catch (final java.text.ParseException e) {
                    e.printStackTrace();
                    return null;
                }
            }
        });

        EntryItem[] items = builder.create().fromJson(reader, EntryItem[].class);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-09-26
    • 1970-01-01
    • 1970-01-01
    • 2013-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多