无法与GSON共享偏好

时间:2018-03-29 20:31:59

标签: android gson sharedpreferences

我有一堆保存在SharedPreference中的地图和数组。但是,一个名为algorithms_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);

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

更新:

保存在&#39; prevs&#39;与if子句中提到的相同。准确地说,&#34;算法的结构优先于#34;这会使问题保存如下:

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

更新II:

我保存了HashMap&#34;算法&#34;作为文件并检查它是否是正确的JSON格式。结果是肯定的。所以我的数据被正确解析了。

1 个答案:

答案 0 :(得分:0)

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

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