【发布时间】:2018-10-21 06:06:56
【问题描述】:
我正在做一个项目,我们使用 jsonfile 作为其数据库,因为 SQLite 不符合要求。该项目有一部分在使用词库中的对象时会改变状态(例如1-4)。我使用 JSONArray 来访问数据。当我尝试更改/编辑状态时,它不会保存或写回 jsonfile。相反,它仅适用于应用程序的暂时使用。
从搜索中,会弹出很多使用 gson 的东西。我最终决定使用 gson。
我是 gson 的新手,前几天才开始学习它。我遇到了麻烦。
这是我的 jsonfile 的结构。它有 2 个排列的对象(用户和词库)
{
"users" :
[{
"username": "free",
"password": "free",
"email": "free@gmail.com",
"type": "1"
},
{
"username": "premium",
"password": "premium",
"email": "premium@gmail.com",
"type": "2"
}],
"wordbank" :
[{
"English": "able",
"Cebuano": "kaya",
"Pronunciation": "ká-ya",
"POS": "adjective",
"Audio": "kaya.mp3",
"Status": "0"
},
{
"English": "advice",
"Cebuano": "tambag",
"Pronunciation": "tam-bag",
"POS": "noun",
"Audio": "tambag.mp3",
"Status": "0"
}]
}
从我在教程视频中看到的是,您为其模型创建了一个不同的 java 类。所以我创建了 3 个 java 类。用户、词库和字典(将它们结合起来)。
public class dictionary{
users[] user;
wordbanks[] word;
}
我已经在使用现有的 jsonfile,所以我对其进行了解析并得到了它的 jsonstring。之后我尝试使用
反序列化它jsonstring = readFromFile();//returns string from jsonfile
dictionary list = new Gson().fromJson(jsonstring, dictionary.class);
运行并调试它。但是当我得到结果时。它是空的。
问题: 1.我可以使用gson编辑和保存json文件中的更改吗? 2.我的结构对于二元类是否正确? 3.如何序列化和反序列化?
【问题讨论】: