考虑以下代码片段
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 对象中获取值。有没有更好的方法来组织上面的代码片段?
最佳答案
我建议您开始使用 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
}
关于java - 通过避免太多 json.getString 来组织以下代码片段的更好方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42761619/