read and write data with GSON

后端 未结 5 829
予麋鹿
予麋鹿 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:22

    You can also do this entirely with streams and avoid an intermediate object:

    Vector v;
    
    // This should be reused, so private static final
    Gson gson = new GsonBuilder().create();
    
    // Read from file:
    try (InputStream fileIn = context.openFileInput("myfile.txt", Context.MODE_PRIVATE);
         BufferedInputStream bufferedIn = new BufferedInputStream(fileIn, 65536);
         Reader reader = new InputStreamReader(bufferedIn, StandardCharsets.UTF_8)) {
        gson.fromJson(reader, Vector.class);
    }
    
    v = new Vector(10.0f, 20.0f);
    
    // Write to file
    try (OutputStream fileOut = context.openFileOutput(filename, Context.MODE_PRIVATE);
         OutputStream bufferedOut = new BufferedOutputStream(fileOut, 65536);
         Writer writer = new OutputStreamWriter(bufferedOut)) {
        gson.toJson(v, writer);
    }
    

    Choose buffer sizes appropriately. 64k is flash-friendly, but silly if you only have 1k of data. try-with-resources might also not be supported by some versions of Android.

提交回复
热议问题