将JSON文件保存到内部存储器

时间:2017-03-24 18:52:03

标签: android json

嘿伙计们我现在正在学习JSON。所以一开始我想学习如何创建一个。所以我写了这段代码......

public void writeJsonFile() {
    username = usernameField.getText().toString();
    password = passwordField.getText().toString();
    JSONObject jsonObject = new JSONObject();
    try{
        jsonObject.put("username", username);
        jsonObject.put("password", password);
    }
    catch (JSONException e) {
        e.printStackTrace();
    }
}

但是我遇到了问题...如何将jSON文件保存到appfolder的内部存储器中?什么是再次调用和读取该文件的代码?

2 个答案:

答案 0 :(得分:0)

您可以拨打jsonObject.toString,然后拨打save and read like in the answer to this question。从磁盘读取字符串后,您需要调用

JSONObject jsonObject = new JSONObject(yourString);

将其解析回JsonObject

还有像Gson这样的工具可以帮助你对json序列化做出反对,这有助于避免一些工作。

答案 1 :(得分:0)

保存JSON本身并不是一个好选择。你能做的是:

  1. 将JSON文件转换为String并使用SharedPrefferences保存String,当您从SharedPrefferences获取它时,将其转换回JSON。
  2. 使用数据库(Realm),将您的JSON映射到模型并将该模型保存在数据库中。
  3. 对于用户名/密码案例,我不会做其中任何一项。但我会使用SharedPrefferences并使用不同的密钥独立存储它们。
  4. 请勿忘记SharedPrefferences中的encrypt sensitive data

    如果您真的想将信息保存在文件中,请检查this answer

相关问题