【发布时间】:2016-10-24 01:03:39
【问题描述】:
我试图弄清楚如何将我的待办事项列表保存在一个文件中,然后在我重新打开应用程序时获取它。到目前为止,我的条目已作为字符串正确保存到文件中,但我不知道如何将它们从字符串中取出并显示在屏幕上。我想我必须反序列化它,但我不知道它是如何工作的,非常感谢一些帮助。
这是我的代码示例:
MainActivity.java
public class MainActivity extends AppCompatActivity {
ArrayList<Entry> mEntries;
String json;
Gson gson;
File dir, saveLocation;
FileWriter file1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
gson = new Gson();
try {
BufferedReader br = new BufferedReader(new FileReader(new File(dir,"storage.json")));
Entry e = gson.fromJson(br, Entry.class);
//I'm stuck here, Don't know how to proceed
} catch (FileNotFoundException e) {
e.printStackTrace();
}
@Override
protected void onStop() {
super.onStop();
json = gson.toJson(mEntries);
Log.d("jsondata", json);
try {
dir = getFilesDir();
saveLocation = new File(dir,"storage.json");
file1 = new FileWriter(saveLocation);
file1.write(json);
file1.flush();
file1.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Entry.java
public class Entry {
String S;
boolean b;
public Entry(String S, boolean b) {
this.S = S;
this.b = b;
}
//Getter and Setter methods
文件中保存的json示例:
[{"S":"你好","b":false},{"S":"task1","b":true},{"S":"task2","b":假}]
//这里S是要完成的任务,b是完成与否
【问题讨论】:
-
向我们展示你的 json
-
添加到帖子中
标签: java android json file deserialization