I am struggling to find a good example on how to read and write data in my android app using GSON. Could someone please show me or point me to a good example? I am using thi
How to save your JSON into a file on internal storage:
String filename = "myfile.txt";
Vector v = new Vector(10.0f, 20.0f);
Gson gson = new Gson();
String s = gson.toJson(v);
FileOutputStream outputStream;
try {
outputStream = openFileOutput(filename, Context.MODE_PRIVATE);
outputStream.write(s.getBytes());
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
How to read it back:
FileInputStream fis = context.openFileInput("myfile.txt", Context.MODE_PRIVATE);
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader bufferedReader = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
sb.append(line);
}
String json = sb.toString();
Gson gson = new Gson();
Vector v = gson.fromJson(json, Vector.class);