android - 从文件中检索 JSONObject

标签 android json file-io

我想将 JSONObject 存储在一个文件中。 为此,我将对象转换为字符串,然后将其存储在文件中。 我使用的代码是:

String card_string =  card_object.toString();
//card_object is the JSONObject that I want to store.

f = new File("/sdcard/myfolder/card3.Xcard");
//file 'f' is the file to which I want to store it.

FileWriter  fw = new FileWriter(f);
fw.write(card_string);
fw.close();

代码如我所愿。现在我想从文件中取回那个对象。 我应该怎么做?我对使用什么来读取文件感到困惑? InputStreamFileReaderBufferedReader 或什么。我是 JAVA/android 开发的新手。

请帮忙。欢迎用简单的语言详细解释在不同情况下(像这样)要使用的 I/O 函数。我已经查看了文档,但欢迎您提出建议。

最佳答案

您可以使用此代码读取文件。

BufferedReader input = null;
try {
    input = new BufferedReader(new InputStreamReader(
            openFileInput("jsonfile")));
    String line;
    StringBuffer content = new StringBuffer();
    char[] buffer = new char[1024];
    int num;
    while ((num = input.read(buffer)) > 0) {
        content.append(buffer, 0, num);
    }
        JSONObject jsonObject = new JSONObject(content.toString());

}catch (IOException e) {...}

然后你可以使用你的 jsonObject:

从JSON对象中获取特定的字符串

String name = jsonObject.getString("name"); 

获取特定的整数

int id = jsonObject.getInt("id"); 

获取特定数组

JSONArray jArray = jsonObject.getJSONArray("listMessages"); 

从数组中获取元素

JSONObject msg = jArray.getJSONObject(1);
int id_message = msg.getInt("id_message");

关于android - 从文件中检索 JSONObject,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16480397/

相关文章:

c 从文件读取输入时修剪换行符

android ClassNotFoundException : Didn't find class error

android - 使屏幕底部出现在键盘上方

javascript - JSON 中的键缺少引号

javascript - 替换或管理ajax请求中的json数据

c# - 将字符串下载为文件

java - 如何从 firebase 检索多个数据并将其显示在 TextView 中?

android - Gradle 总是执行任务

ios - 创建 NSDateFormatter 可重用类

c - C 中的基本文件 IO