【问题标题】:Writing child instance variables to JSONObject将子实例变量写入 JSONObject
【发布时间】: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


    【解决方案1】:

    您遇到的问题有两个主要原因:

    • 此方法的功能与特定类的需求紧密耦合。因此,很难在其他类中重用。

    • 该方法本身违反了 SOLID 的第一条原则,Single responsibility principle,它指出一个类应该只有一个改变的理由。但是createActivity() 中发生了很多事情:它从文件中读取 JSON,它改变了 JSONobject,它更新了文件。

    基本上,可以观察到的所有功能createActivity() 不应该与任何类耦合。相反,该方法可以拆分为多个static 方法,每个方法代表一个单独的职责。并且这个方法可以分组到一个 Utility 类中。

    这就是此类的样子:

    public static class JsonUtils {
        
        private JsonUtils() {} // no way and no need to invoke the constructor of this class
    
        public JSONObject readFromFile(Path path) throws IOException {
            
            String json = Files.readString(path);
            return new JSONObject(json);
        }
    
        public void updateJsonObject(Map<String, ?> map, JSONObject json) {
            
            map.forEach(json::put);
        }
    
        public void writeToFile(Path path, JSONObject json) throws IOException {
            
            Files.writeString(path,json.toString());
        }
    
        public void writeToFile(Path path, JSONObject json, OpenOption... options) throws IOException {
        
            Files.writeString(path,json.toString(), options);
        }
        
        // other methods
    }
    

    笔记:File 类是遗留的。推荐的替代方法是使用 NIO API 中的Path。如果你使用 NIO.2 中的Files 实用程序类,如上例所示,它将极大地简化 IO 处理方法的代码。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-01
      • 2022-12-22
      • 2015-04-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多