【问题标题】:ANDROID : deserialise json string from file to class objectANDROID:将json字符串从文件反序列化为类对象
【发布时间】: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


【解决方案1】:

你的代码是正确的。

Entry e = gson.fromJson(br, Entry.class); 

这行代码已经反序列化了字符串。

【讨论】:

  • 但是怎么做呢?如果我这样做,我将如何获得所有条目?以及如何在屏幕上显示?
  • ArrayList tmp = gson.fromJson(json, ArrayList.class);或 ArrayList tmp = gson.fromJson(json, Entry[].class);
  • 我收到类似这样的错误:java.lang.NullPointerException: Attempt to invoke virtual method 'int java.util.ArrayList.size()' on an null object reference at calpoly.edu.challenge4 .MyAdapter.getItemCount(MyAdapter.java:54)
【解决方案2】:

由于您的文件包含 Json 数组,您应该将其解析为 Entry 的数组,而不是 Entry 的单个实例,例如:

BufferedReader br = new BufferedReader(new FileReader(new File(dir,"storage.json")));
Entry[] entries = gson.fromJson(br, Entry[].class); 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-01-04
    • 2020-02-03
    • 1970-01-01
    • 2012-04-24
    • 1970-01-01
    • 1970-01-01
    • 2016-03-06
    相关资源
    最近更新 更多