2015-10-02 37 views
2

我對android非常陌生,正在練習使用toJson和fromJson將類對象添加到文件。我設法將我的對象寫入txt文件,但我不知道如何使用fromJson從那裏取回它。所有的代碼如下: 初始化onCreate方法中:如何使用toJson和fromJson從Json文件中獲取對象

cookie1.income=10; 
    cookie1.cookieNumber=1; 
    writeObject(cookie1); 

-

public void writeObject(cookie cookie1){ 
    Gson gson = new Gson(); 
    String s = gson.toJson(cookie1); 
    FileOutputStream outputStream; 

    try { 
     outputStream = openFileOutput("file.txt", Context.MODE_PRIVATE); 
     outputStream.write(s.getBytes()); 
     outputStream.close(); 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 
} 

-

public class cookie{ 
long cookieNumber; 
long income; 
} 

這裏是我在我的txt文件

{"coockieNumber":1,"income":10} 
+0

通過InputStream讀取文件,然後將字符串傳遞給Gson以獲取數據。 – bilal

回答

1

使用這個函數來讀取co文件的內容。

private String readFile() throws IOException { 

     FileInputStream fis = openFileInput("file.txt"); 

     int c; 
     String temp=""; 
     while((c = fis.read()) != -1){ 
      temp = temp + Character.toString((char)c); 
     } 

     fis.close(); 
     return temp; 
} 

然後,

String data = null; 

    try{ 

    data = readFile(); 

    } catch(IOException e) {} 

data conatins你的文件的內容。現在使用Gson

if(data != null) { 
    cookie obj = new Gson().fromJson(data, cookie.class); 
} 
+0

謝謝,它幫助! –