通过避免太多json.getString来组织以下代码段的更好方法

时间:2017-03-13 10:42:03

标签: java oop design-patterns

考虑以下代码段

public static JSONObject getStudentDetails() throws Exception {
//returns the details as json
}

public static JSONObject getDepartmentDetails(String department_id) throws Exception {
//returns the details as json
}

public void doPost(HttpServletRequest req, HttpServletResponse res) throws Exception {

JSONObject json1 = getStudentDetails();
String name = json1.getString(“name”);
String role_number = json1.getString(“role_number”);
String department_id = json1.getStrring(“department_id”);
//and goes on - to get all student details


JSONObject json2 = getDepartmentDetails(department_id);
String department_hod = json2.getString(“department_hod”);
String department_name = json2.getString(“department_name”);
String department_block = json2.getString(“department_block”);
//and goes on - till i get all the department details

//Followed by main action to be performed
}

在大多数情况的上面的代码中,我可能会调用一个util方法,它返回一个json对象,我在doGet / doPost方法中使用它。因此,我的doPost / doGet中的大部分代码都是使用getString从json对象获取值。有没有更好的方法来组织上述代码段?

1 个答案:

答案 0 :(得分:1)

我建议您开始使用JSON解析器库。有一些着名的JSON解析器库,例如:FastJSON,Jackson,Gson等。

如果您不想使用任何外部库,为了更清晰的代码,您最好创建一个模型来将数据放在那里,并确保在命名变量时尽可能清楚。因为没有外部库的帮助就无法避免 json.getString

class Student{
    private String name;
    private String roleNumber;
    private String departmentId;

    public String getName() {
        return name;
    }

    public Student setName(String name) {
        this.name = name;
        return this;
    }

    public String getRoleNumber() {
        return roleNumber;
    }

    public Student setRoleNumber(String roleNumber) {
        this.roleNumber = roleNumber;
        return this;
    }

    public String getDepartmentId() {
        return departmentId;
    }

    public Student setDepartmentId(String departmentId) {
        this.departmentId = departmentId;
        return this;
    }
}

public void doPost(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
    JSONObject studentJsonObject = getStudentDetails();
    Student student = new Student()
            .setName(studentJsonObject.getString("name"))
            .setRoleNumber(studentJsonObject.getString("role_number"))
            .setDepartmentId(studentJsonObject.getString("department_id"));

    //then you can easily get each property of student
    //like student.getName(); or student.getDepartmentId();

    //the rest of your code
}