我试图写入一个json文件,它只是不工作,我没有得到任何错误,但没有任何变化的文件。
下面是我的代码的相关部分
try {
//method1
Gson gson = new Gson();
String s = "gjsanhfhj";
String path = this.getApplicationContext().getFilesDir().getAbsolutePath() + "/" + "test.json";
File file = new File(path);
file.setWritable(true);
gson.toJson(s,new FileWriter(file));
//method2
FileOutputStream outputStream;
outputStream = openFileOutput(path, Context.MODE_PRIVATE);
outputStream.write(s.getBytes());
outputStream.close();
//method3
Writer output;
output = new BufferedWriter(new FileWriter(file));
output.write(s);
output.close();
Toast.makeText(this.getApplicationContext(), "check", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
我试了上面的3种方法,都不起作用,我找不到其他的方法
我试过这个
public class PlayerData {
private int gold;
private int wins;
private int losses;
public PlayerData(){
gold = 0;
wins = 0;
losses = 0;
}
Gson gson = new Gson();
String path = this.getApplicationContext().getFilesDir().getAbsolutePath() + "/" + "test.json";
File file = new File(path);
file.setWritable(true);
gson.toJson(new PlayerData(),new FileWriter(file));
不工作
2条答案
按热度按时间3yhwsihp1#
试试这个我觉得很管用
yr9zkbsy2#
Gson.toJson(Obj)用于将对象转换为Json-String,Json-String是一个键值对。Gson.toJson()以java对象作为参数,而你传递的是一个STRING值,我认为这是不正确的。例如,Employee类的对象,可以转换为json如下所示。
{\fnSimHei\bord1\shad1\pos(200,288)}
现在,你可以打电话
所以,请再次检查您的要求。