java - Android从url写入json文件

标签 java android json

我正在处理 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/

相关文章:

java - Jackson 异常的序列化和反序列化

c# - 如何跳过 Json.Net 中 IEnumerable 类型的默认 JavaScript 数组序列化?

java - Flying Saucer : Convert Multiple Html to 1 PDF document

java - 使用 SingularAttribute 中的 getName() 函数时出现 NullPointerException

java - 不再需要 Android O 转换为 findViewById?

android - 如何在android sqlite数据库中使用查询

java - Android Function 返回一个数组直接变成变量

java - Gradle jpackage 创建无法运行的应用程序

java - 从 Java 访问 OneNote API

mysql - 将 JSON 输入插入 MySQL 表