我正在处理 JSON。我编写了可以解析 JSON 并显示 ListView (图像和文本)的代码。 现在我想将 JSON 保存在文件 (json.txt) 中。 这是我的代码。我尝试保存 JSON,但是当我在 json.txt 文件上调试它时,仅保存了第一个数据,但 JSON 中有 20 个数据 如果有人知道解决方案请帮忙......
jsonparser = new JSONParser();
JSONObject jsonobject = jsonparser.getJSONfromURL(URL);
try {
jsonarray = jsonobject.getJSONArray("data");
for (int i = 0; i < jsonarray.length(); i++) {
jsonobject = jsonarray.getJSONObject(i);
HashMap<String, String> map = new HashMap<String, String>();
map.put("journal", jsonobject.getString(KEY_journal));
map.put("image", jsonobject.getString(KEY_image));
map.put("title", jsonobject.getString(KEY_title));
map.put("description",
jsonobject.getString(KEY_description));
map.put("JournalID", jsonobject.getString(KEY_JournalID));
map.put("pubDate", jsonobject.getString(KEY_pubDate));
map.put("statID", jsonobject.getString(KEY_statID));
Content cont = new Content(jsonobject.getString("journal"),
jsonobject.getString("image"),
jsonobject.getString("title"),
jsonobject.getString("pubDate"),
jsonobject.getString("description"),
jsonobject.getString("JournalID"),
jsonobject.getString("statID"));
contents.add(cont);
yourFile = new File("/sdcard/json.txt");
try {
writer = new OutputStreamWriter(
new FileOutputStream(yourFile), "UTF-8");
writer.write(jsonobject.toString());
writer.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (writer != null) {
try {
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
最佳答案
以追加模式打开文件。
new OutputStreamWriter(new FileOutputStream(yourFile,true), "UTF-8");
关于java - Android从url写入json文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21455143/