【问题标题】:Can not get shared preference with GSON无法与 GSON 共享偏好
【发布时间】:2018-09-08 21:53:02
【问题描述】:

我有一堆 Maps 和 Arrays 保存在 SharedPreference 中。然而,一个名为 algorithm_tmp 的 Map 会抛出一个名为:

Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 9 path $.

其他 ArrayList 和 HashMap 被正确处理。代码如下:

Gson gson = new Gson();
SharedPreferences prefs = getSharedPreferences("OverViewPref", MODE_PRIVATE);

String pref_algorithms = prefs.getString("algorithms","");
String pref_algorithmNames = prefs.getString("algorithmNames","");
String pref_algorithm_information = prefs.getString("algorithm_information","");

Type type_algorithms = new TypeToken<HashMap<String, HashSet<String>>>(){}.getType();
Type type_algorithmNames = new TypeToken<ArrayList<String>>(){}.getType();
Type type_algorithm_information = new TypeToken<HashMap<String,String>>(){}.getType();

boolean bool_algorithms= prefs.contains("algorithms");
boolean bool_algorithmsNames=prefs.contains("algorithmNames");
boolean bool_algorithm_information=prefs.contains("algorithm_information");


if(bool_algorithms && bool_algorithmsNames && bool_algorithm_information){
    HashMap<String,HashMap<String,HashSet<String>>> algorithms_tmp= gson.fromJson(pref_algorithms, type_algorithms);
    HashMap<String,String> algorithm_information_tmp= gson.fromJson(pref_algorithm_information, type_algorithm_information);
    ArrayList<String> algorithmNames_tmp= gson.fromJson(pref_algorithmNames, type_algorithmNames);

    algorithms.putAll(algorithms_tmp);
    algorithmNames.addAll(algorithmNames_tmp);
    algorithm_information.putAll(algorithm_information_tmp);
}

错误在以下代码行中引发:

HashMap<String,HashMap<String,HashSet<String>>> algorithms_tmp= gson.fromJson(pref_algorithms, type_algorithms);

Google 没有帮助我解决我的问题。我在这里做错了什么?

更新:

保存到“prevs”的结构与 if 子句中提到的相同。准确地说,这里出现问题的“算法首选项”的结构保存如下:

 {  
   "CPM":{  
      "Cluster8":[  
         "115",
         "262",
         "312",
         "220"
      ], ...
   },
   "Infomap":{  
      "Cluster5":[  
         "273",
         "152",
         "78",
         "4",
         "275",
         "195",
         "218",
         "181",
         "306",
         "328"
      ], ...
   }, ...
}

更新二:

我将 HashMap“算法”保存为一个文件,并检查它是否为正确的 JSON 格式。结果是肯定的。所以我的数据被正确解析了。

【问题讨论】:

  • 我们需要查看您保存到首选项的结构
  • 我添加了如何保存“算法”的结构。当我打印首选项时,它会正确输出。然而,转换在前面提到的那个时候每次都会失败

标签: android gson sharedpreferences


【解决方案1】:

解决了这个问题。 type_algorithms 的 TypeToken 错误。它必须是类型:

HashMap<String,HashMap<String,HashSet<String>>>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-08-03
    • 2013-05-08
    • 1970-01-01
    • 2014-07-29
    • 2019-03-20
    • 1970-01-01
    相关资源
    最近更新 更多