2013-10-18 271 views
9

我很努力地找到一個很好的例子,說明如何使用GSON在我的android應用程序中讀取和寫入數據。有人可以指給我看一個好例子嗎?我正在使用它來進行活動之間的數據持久性。使用GSON讀取和寫入數據

我的教授給這個例子來寫:

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

我怎麼會去那個保存到一個文件?

+0

這似乎不是與Gson的問題,似乎你正在尋找有關在Android設備上創建文件的信息... –

+0

@RayStojonic我從來沒有說過這是一個問題。我無法找到有關如何使用它的任何好信息。 – Deekor

+0

也許這可以幫助你:http://developer.android.com/training/basics/data-storage/files.html – giampaolo

回答

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

openFileInput只接受一個需要是字符串的參數。 – Cappuccino90

+0

以及上下文是什麼? – Line

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這樣簡單的東西開始。

希望得到這個幫助! :]

UPDATE:

如果你真的想要寫在一個文件中的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方式。

+0

感謝這個例子。我將如何編寫這些json文件? – Deekor

+0

我更新了答案。 – 4gus71n

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