read and write data with GSON

后端 未结 5 725
予麋鹿
予麋鹿 2021-01-11 21:23

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

5条回答
  •  囚心锁ツ
    2021-01-11 22:10

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

提交回复
热议问题