我是 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/