Im trying to write into a json file and it just doesnt work, I dont get any errors but nothing changes in the file.
here is the relevant section of my code
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();
}
I tried the 3 methods above, didnt work I couldnt find anything else
I tried this
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));
didnt work
2
Answers
Gson.toJson(Obj) is used to convert an object into a Json-String which is a key value pair. Gson.toJson() takes a java object as an argument, whereas, you are passing a STRING value which not right, I think. For example, an object of Employee class, can be converted into json as below.
} `
Now, you can call
So, please check your requirement again.
Try this. This worked for me.