read and write data with GSON

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

    Simple Gson example:

    public class Main {
    
        public class Power {
            private String name;
            private Long damage;
    
            public String getName() {
                return name;
            }
    
            public void setName(String name) {
                this.name = name;
            }
    
            public Long getDamage() {
                return damage;
            }
    
            public void setDamage(Long damage) {
                this.damage = damage;
            }
    
            public Power() {
                super();
            }
    
            public Power(String name, Long damage) {
                super();
                this.name = name;
                this.damage = damage;
            }
    
            @Override
            public String toString() {
                return "Power [name=" + name + ", damage=" + damage + "]";
            }
    
        }
    
        public class Warrior {
            private String name;
            private Power power;
    
            public String getName() {
                return name;
            }
    
            public void setName(String name) {
                this.name = name;
            }
    
            public Power getPower() {
                return power;
            }
    
            public void setPower(Power power) {
                this.power = power;
            }
    
            public Warrior() {
                super();
            }
    
            public Warrior(String name, Power power) {
                super();
                this.name = name;
                this.power = power;
            }
    
            @Override
            public String toString() {
                return "Warrior [name=" + name + ", power=" + power.toString() + "]";
            }
    
        }
    
        public static void main(String[] args) {
            Main m = new Main();
            m.run();
        }
    
        private void run() {
            Warrior jake = new Warrior("Jake the dog", new Power("Rubber hand", 123l));
            String jsonJake = new Gson().toJson(jake);
            System.out.println("Json:"+jsonJake);
            Warrior returnToWarrior = new Gson().fromJson(jsonJake, Warrior.class);
            System.out.println("Object:"+returnToWarrior.toString());
        }
    
    }
    

    Anyways checkout the documentation.

    And to persist something in your application you can start with something simple like ORMlite.

    Hope this help! :]

    UPDATE:

    If you really want write the json in a file:

            File myFile = new File("/sdcard/myjsonstuff.txt");
            myFile.createNewFile();
            FileOutputStream fOut = new FileOutputStream(myFile);
            OutputStreamWriter myOutWriter =new OutputStreamWriter(fOut);
            myOutWriter.append(myJsonString);
            myOutWriter.close();
            fOut.close();
    

    And if you want to read:

            File myFile = new File("/sdcard/myjsonstuff.txt");
            FileInputStream fIn = new FileInputStream(myFile);
            BufferedReader myReader = new BufferedReader(new InputStreamReader(fIn));
            String aDataRow = "";
            String aBuffer = ""; //Holds the text
            while ((aDataRow = myReader.readLine()) != null) 
            {
                aBuffer += aDataRow ;
            }
            myReader.close();
    

    Also add: <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> to your manifest.

    But, seriously is so much better use a ORM and store the records in the db. I don't know why you need save the json data in a file, but if I was you, I will use the ORM way.

    0 讨论(0)
  • 2021-01-11 22:07

    Maybe in more recent version, but toJson accepts writer that directly writes to file.

    ex.:

    Vector v = new Vector(10.0f, 20.0f);
    Gson gson = new GsonBuilder().create(); 
    Writer writerJ = new FileWriter("keep.json");
    gson.toJson(v,writerJ);
    
    0 讨论(0)
  • 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);
    
    0 讨论(0)
  • 2021-01-11 22:19

    Save your class in SharedPrefrences using

    public static void saveYourClassInSharedPref(ClassToSave ClassToSave) {
            try{
                String json = "";
                if(ClassToSave != null){
                    json = new Gson().toJson(ClassToSave);
                }
                SharedPref.save(KeysSharedPrefs.ClassToSave, json);
            }catch (Exception ex){
                ex.printStackTrace();
            }
    
        }
    
        public static ClassToSave readYourClassFromSharedPref() {
            ClassToSave ClassToSave;
            try{
                String json = SharedPref.read(KeysSharedPrefs.ClassToSave, "");
                if(!json.isEmpty()){
                    ClassToSave = new Gson().fromJson(json, ClassToSave.class);
                    return ClassToSave;
                }
            }catch (Exception ex){
                ex.printStackTrace();
            }
            return null;
        }
    

    where SharedPref.java

    public class SharedPref {
    
        public static String read(String valueKey, String valueDefault) {
            SharedPreferences prefs = PreferenceManager
                    .getDefaultSharedPreferences(App.context);
            return prefs.getString(valueKey, valueDefault);
        }
    
        public static void save(String valueKey, String value) {
            SharedPreferences prefs = PreferenceManager
                    .getDefaultSharedPreferences(App.context);
            SharedPreferences.Editor edit = prefs.edit();
            edit.putString(valueKey, value);
            edit.commit();
        }
    }
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题