从文件中检索JSONObject

nee*_*rle 2 file-io android json

我想存储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();
Run Code Online (Sandbox Code Playgroud)

该代码按我的意愿工作。现在,我从文件中检索该对象。我该怎么办?我对使用什么读取文件感到困惑?一个InputStreamFileReaderBufferedReader或什么。我是JAVA / android开发的新手。

请帮忙。欢迎用简单的语言详细说明在不同情况下(例如这样)要使用哪些I / O功能。我看过文档,但是欢迎您提出建议。

Gab*_*tti 5

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

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) {...}
Run Code Online (Sandbox Code Playgroud)

然后,您可以使用jsonObject:

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

String name = jsonObject.getString("name"); 
Run Code Online (Sandbox Code Playgroud)

获取特定的int

int id = jsonObject.getInt("id"); 
Run Code Online (Sandbox Code Playgroud)

获取特定的数组

JSONArray jArray = jsonObject.getJSONArray("listMessages"); 
Run Code Online (Sandbox Code Playgroud)

从数组中获取项目

JSONObject msg = jArray.getJSONObject(1);
int id_message = msg.getInt("id_message");
Run Code Online (Sandbox Code Playgroud)