【问题标题】:Android: save gson.toJson() return string on my sdcardAndroid:在我的 sdcard 上保存 gson.toJson() 返回字符串
【发布时间】:2012-12-25 21:50:18
【问题描述】:

我正在尝试让应用程序将一些 Json 数据保存在本地文件中(在 sdcard 上)..

第一次运行时,我只需要将 json-data 保存在一个文件中...

然后返回“applications_arr”(不是来自文件,而是来自 JsonReader)

查看holde asyncTask-class here

还有ApplicationsModel.class(实现 Parcelable)


amFile = new File(this.activity.getFilesDir()+"/applications"+UUID.randomUUID()+".json");
gson = new GsonBuilder().create();

reader = new JsonReader(new BufferedReader(new InputStreamReader(new URL("http://software-center.ubuntu.com/api/2.0/applications/any/ubuntu/any/any/").openConnection().getInputStream())));
reader.beginArray();

//save am-json-data on sdcard
FileWriter fw = new FileWriter(amFile.getAbsoluteFile());
fw.write(gson.toJson(reader, ApplicationsModel.class));
fw.close();

//create am-arraylist to use now.. amFile is other use      
while (reader.hasNext()) {
    ApplicationsModel model = gson.fromJson(reader, ApplicationsModel.class);
    applications_arr.add(model);
}
reader.endArray();
reader.close();

看起来错误是:

fw.write(gson.toJson(reader, ApplicationsModel.class));

我的 Logcat 看起来像 this

【问题讨论】:

  • 错误是什么,您在 logcat 中是否有任何内容,或者您​​根本没有得到预期的结果?
  • Yes logcat say FATAL EXCEPTION: AsyncTask #2.. 我已经用 logcat-drop 更新了这个问题。

标签: java android io gson java-io


【解决方案1】:

您可能需要在您的manifest 中指定WRITE_EXTERNAL_STORAGE 权限。

这看起来像:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

编辑:

查看你的logcat,错误是:

java.util.concurrent.ExecutionException: java.lang.IllegalArgumentException:类型的预期接收者 com.ubuntu.apps.ApplicationsModel,不是 com.google.gson.stream.JsonReader

这说明 Gson 期望在 ApplicationModel 中读取,而您却给它一个 JsonReader。

也就是说,您尝试保存正在从 URL 流式传输到文件的 Json 的行不需要 Gson。只需将 Json 直接流式传输到文件即可。

【讨论】:

  • 我的清单中包含 WRITE_EXTERNAL_STORAGE 以及 ACCESS_NETWORK_STATE 和 INTERNET。所以这不是错误!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-02-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多