使用GSON读写数据

时间:2013-10-18 21:07:43

标签: java android gson

我很难找到一个关于如何使用GSON在我的Android应用程序中读取和写入数据的好例子。有人可以告诉我或指出一个很好的例子吗?我正在使用它来实现活动之间的数据持久性。

我的教授给了这个例子写作:

Vector v = new Vector(10.0f, 20.0f);
Gson gson = new Gson();
String s = gson.toJson(v);

我如何将其保存到文件中?

5 个答案:

答案 0 :(得分:18)

如何将JSON保存到内部存储上的文件中:

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

如何阅读:

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

答案 1 :(得分:9)

简单的Gson示例:

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

}

无论如何都要结帐documentation

要在应用程序中保留某些内容,您可以从简单的ORMlite开始。

希望这有帮助! :

<强>更新

如果你真的想在文件中写json:

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

如果你想阅读:

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

同时添加:<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> 到你的清单。

但是,使用ORM并将记录存储在数据库中是非常好的。我不知道为什么你需要将json数据保存在文件中,但如果我是你,我将使用ORM方式。

答案 2 :(得分:0)

使用

将您的课程保存在SharedPrefrences中
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;
    }

其中 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();
    }
}

答案 3 :(得分:0)

也许在更新的版本中,但是toJson接受直接写入文件的编写者。

例如:

Vector v = new Vector(10.0f, 20.0f);
Gson gson = new GsonBuilder().create(); 
Writer writerJ = new FileWriter("keep.json");
gson.toJson(v,writerJ);

答案 4 :(得分:0)

您也可以使用流完全执行此操作并避免使用中间对象:

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

适当选择缓冲区大小。 64k是闪存友好的,但如果你只有1k的数据,那就太傻了。某些版本的Android也可能不支持try-with-resources。