【发布时间】:2022-10-23 16:33:15
【问题描述】:
所以最近我想出了如何在 java 中使用 JSON,并创建了在我的 JSON 数据库中写入、读取和更新信息(主要是类)的代码。在我的“活动”类中,我有一个将类对象写入 JSON 的方法:
public void createActivity() {
File file = database;
JSONObject newActivity = new JSONObject();
setRegDate(LocalDate.now());
try {
actID = IO.getJsonArray(file, "Activities").length() + 1;
} catch (Exception e) {
System.out.println("Exception: Could not set new activity ID.");
}
newActivity.put("userID", userID);
newActivity.put("actDate", actDate);
newActivity.put("regDate", regDate);
newActivity.put("actID", actID);
newActivity.put("description", description);
newActivity.put("coach", coach);
try {//Writes new user JSONObject to account file.
IO.putObjInArr(file, newActivity, "Activities");
} catch (Exception e) {
System.out.println("Exception: Creating activity failed.");
}
}
随着学习过程的继续,我现在在我的项目中添加了子类。一个子类可能包含实例变量“距离”和“时间”。有几个子类。
当然,现在我不想将上述方法复制到每个子类中,并在那里添加特定的变量。我希望所有这些都集中在一个父类中。
我想知道,是否有可能以某种方式遍历所有可能的子类变量,以便我可以将它们写入 JSON?或者子变量对父级根本不可见,更不用说如果我不向父级指定这些变量可能是哪些变量?
目前,我能想到的就是将子类的所有实例变量放在一个 hashmap 中,将它们作为参数发送给 Activity.createActivity,然后循环遍历 hashmap 的所有元素。
【问题讨论】:
标签: java json parent-child org.json