【发布时间】:2019-07-22 07:25:27
【问题描述】:
我将我的 JSONObject 保存到磁盘,然后当我尝试将它加载回 JSONObject 时,我在 loadSavedScheduleFromDisk 方法的这一行得到以下异常:
JSONObject jsonObject = gson.fromJson(reader, JSONObject.class);
com.google.gson.JsonSyntaxException:com.google.gson.stream.MalformedJsonException:第 1 行第 74040 列路径 $.nameValuePairs..values[32].values[2].nameValuePairs.disciplineVersionId 的未终止字符串
这是我的代码:
private void loadSavedScheduleFromDisk(Activity act) {
try {
File file = new File(((Context)act).getCacheDir()+"/"+SCHED_CACHE_FILENAME);
Gson gson = new Gson();
InputStreamReader freader = new InputStreamReader(new FileInputStream(file), Charset.forName("UTF-8"));
JsonReader reader = new JsonReader(freader);//new FileReader(file));
reader.setLenient(true);
JSONObject jsonObject = gson.fromJson(reader, JSONObject.class);
parseSchedule(jsonObject);
} catch (Exception e) {
e.printStackTrace();
}
}
private void saveScheduleToDisk(Activity act, JSONObject jsonObject )
{
try {
File file = new File(((Context)act).getCacheDir()+"/"+SCHED_CACHE_FILENAME);
//Writer writer = new FileWriter(file);
Writer writer = new OutputStreamWriter(new FileOutputStream(file), Charset.forName("UTF-8"));
Gson gson = new GsonBuilder().create();
gson.toJson(jsonObject, writer);
} catch (Exception e) {
e.printStackTrace();
}
}
它非常对称,我不明白为什么它不起作用 - 我想如果我使用 API 将我的 JSONObject 保存到磁盘并且保存正常,那么为什么我不能加载相同的数据呢?
【问题讨论】:
-
一个更简单的选择是将其保存为共享首选项上的字符串,然后创建Json from string。
-
您的
JSON有效吗?您可以在此路径下找到什么:$.nameValuePairs..values[32].values[2].nameValuePairs.disciplineVersionId? -
我相信我的 JSON 是有效的,因为我已经在 saveScheduleToDisk() 方法中将它作为 JSONObject 保存在内存中。在保存到磁盘之前,我还从服务器加载了这个 JSON,一切正常。
-
我没有尝试共享首选项,因为我在某处读到它用于保存小字符串。在我的情况下,这个 JSON 可以是 800Kb 甚至更多,但如果没有任何帮助,我会试一试
-
@Michal 我没有发现这些值有什么问题,我一解决这个问题就会在这里发布我的解决方案