ANDROID:如何将数据插入 JSON 文件并将其保存到本地存储?

因此,我计划将输入的数据存储到 JSON 文件中,并且希望将该 JSON 文件存储到手机的本地存储中。但是我的代码中有这个错误。这是关于 JsonWriter。谁能帮我?


// THIS IS MY CODE


private void writeToFile(OutputStream out, List<Wordbank> wordList) throws IOException{

    JsonWriter writer = new JsonWriter(new OutputStreamWriter(out, "UTF-8"));

    writer.setIndent(" ");

    writeWordbankArray(writer, wordList);

    writer.close();

}


public void writeWordbankArray(JsonWriter writer, List<Wordbank> wordList) throws  IOException{

    writer.beginArray();

    for(Wordbank wl : wordList){

        writeWordbank(writer, wl);

    }

    writer.endArray();

}


public void writeWordbank(JsonWriter writer, Wordbank wordbank) throws IOException{

    writer.beginObject();

    writer.name("English").value(wordbank.getEnglish());

    writer.name("Cebuano").value(wordbank.getCebuano());

    writer.name("Pronounciation").value(wordbank.getPronounciation());

    writer.name("POS").value(wordbank.getPos());

    writer.name("Audio").value(wordbank.getAudio());

    if(wordbank.getImage() != null || wordbank.getFx() != null){

        writer.name("Picture").value(wordbank.getImage());

        writer.name("Effect").value(wordbank.getFx());

    }else{

        writer.name("No name").nullValue();

    }

    writer.endObject();

}

// 下面是错误


2018-10-18 18:48:52.372 4965-4965/com.example.sampleFile/AndroidRuntime: FATAL EXCEPTION: main

Process: com.example.sampleFile, PID: 4965

以上是错误。我需要这方面的帮助,请帮帮我!


牧羊人nacy
浏览 680回答 2
2回答

繁星淼淼

您可以使用另一种方法。以下代码writer.name("English").value(wordbank.getEnglish());writer.name("Cebuano").value(wordbank.getCebuano());writer.name("Pronounciation").value(wordbank.getPronounciation());writer.name("POS").value(wordbank.getPos());writer.name("Audio").value(wordbank.getAudio());if(wordbank.getImage() != null || wordbank.getFx() != null){&nbsp; &nbsp; writer.name("Picture").value(wordbank.getImage());&nbsp; &nbsp; writer.name("Effect").value(wordbank.getFx());}else{&nbsp; &nbsp; writer.name("No name").nullValue();}告诉我您已经知道会发生什么,您可以创建一个 POJO 类并使用 Gson 库将该 POJO 对象解析为 JSON 格式的字符串。稍后您可以将其用作JSONObject jsonObj = new JSONObject(Jsonstring);这是一个例子ModelPOJO modelPojo = new ModelPojo();modelPojo.setEnglish("value");Gson gson = new Gson();String jsonString = gson.toJson(modelPojo);jsonString 是必需的字符串。要将其写入本地存储,您可以采用@jake breen 的方法。希望能帮助到你 !:)

白板的微信

try {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; File file = new File("<storage location>" + filename + ".json");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Writer writer = new BufferedWriter(new FileWriter(file));&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; writer.write(jsonObject.toString());&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; writer.close();&nbsp; &nbsp; &nbsp; &nbsp; } catch (Exception e) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Log.e("File Exception: ", e.getMessage());&nbsp; &nbsp; &nbsp; &nbsp; }
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java