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

时间:2015-10-02 05:19:40

标签: 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}

1 个答案:

答案 0 :(得分:1)

使用此功能可读取文件内容。

 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);
}