android - 如何使用 toJson 和 fromJson 从 Json 文件中获取对象

标签 android json

我是 android 的新手,正在练习使用 toJson 和 fromJson 将类对象添加到文件中。我设法将我的对象写入 txt 文件,但我不知道如何使用 fromJson 从那里取回它。所有代码如下: onCreate 方法中的初始化:

cookie1.income=10;
    cookie1.cookieNumber=1;
    writeObject(cookie1);

-

public void writeObject(cookie cookie1){
    Gson gson = new Gson();
    String s = gson.toJson(cookie1);
    FileOutputStream outputStream;

    try {
        outputStream = openFileOutput("file.txt", Context.MODE_PRIVATE);
        outputStream.write(s.getBytes());
        outputStream.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

-

public class cookie{
long cookieNumber;
long income;
}

这是我的txt文件中的内容

{"coockieNumber":1,"income":10}

最佳答案

使用这个函数读取文件的内容。

 private String readFile() throws IOException {

        FileInputStream fis = openFileInput("file.txt");

        int c;
        String temp="";
        while( (c = fis.read()) != -1){
            temp = temp + Character.toString((char)c);
        }

        fis.close();
        return temp;
}

然后,

String data = null;

    try{

    data = readFile();

    } catch(IOException e) {}

data 包含文件的内容。现在使用 Gson

    if(data != null) {
    cookie obj = new Gson().fromJson(data, cookie.class);
}

关于android - 如何使用 toJson 和 fromJson 从 Json 文件中获取对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32900975/

相关文章:

java - 在android中通过php检索Json数据?

java - 如何使用平移动画

json - Microsoft Flow SharePoint 到 Teams HTTP 413

javascript - 显示 json 数组中的所有项目

json - 使用接口(interface)解码 json 数据时出错?

Java 方法流程

android - 检查回收站中位置的文本

android - 无法从中加载模块元数据

javascript - Vuejs 从数据属性返回 [object Object]

objective-c - 如何将 JSON 解析为 Objective C - SBJSON