Java 通过避免过多的json.getString,更好地组织以下代码段
考虑以下代码段Java 通过避免过多的json.getString,更好地组织以下代码段,java,oop,design-patterns,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(HttpSe
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方法,该方法返回我在doGet/doPost方法中使用的json对象。因此,doPost/doGet中的大部分代码类似于使用getString从json对象获取值。有没有更好的方法来组织上述代码段?我建议您开始使用JSON解析器库。有一些著名的JSON解析器库,例如:FastJSON、Jackson、Gson等 如果您不想使用任何外部库,为了获得更清晰的代码,最好创建一个模型将数据放在那里,并确保在命名变量时尽可能清晰。因为没有外部库的帮助,无法避免json.getString
你试过像Gson或FastJSON这样的json解析器库吗?没有。。考虑到序列化和反序列化对于多个小型JSON来说成本更高……那么你应该开始使用其中的一个,因为它会让你的生活更轻松,让你的代码更好更干净。我建议您从FastJSON开始,因为就性能而言,它是最好的json解析器序列化器/反序列化器。键入其他代码对您的时间和键盘寿命来说代价更高
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
}