9

我正在努力寻找一个关于如何使用 GSON 在我的 android 应用程序中读取和写入数据的好例子。有人可以告诉我或指出一个很好的例子吗?我将其用于活动之间的数据持久性。

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

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

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

4

5 回答 5

19

如何将 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);
于 2013-10-18T22:20:29.293 回答
10

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

}

无论如何检查文档

为了在你的应用程序中保留一些东西,你可以从像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 方式。

于 2013-10-18T22:14:46.963 回答
1

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

前任。:

Vector v = new Vector(10.0f, 20.0f);
Gson gson = new GsonBuilder().create(); 
Writer writerJ = new FileWriter("keep.json");
gson.toJson(v,writerJ);
于 2017-11-18T20:24:30.483 回答
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();
    }
}
于 2016-08-03T06:48:31.183 回答
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。

于 2017-12-01T23:57:48.523 回答