1
組織下面的代碼片段
考慮下面的代碼片段通過避免太多json.getString
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
}
在大多數情況下我可能會調用,它返回一個JSON對象的方法UTIL上面的代碼更好的辦法我正在使用我的doGet/doPost方法。因此,我的doPost/doGet中的大部分代碼就像從getString
中獲取json對象的值。有沒有更好的方法來組織上面的代碼片段?
你有沒有試過像Gson或FastJSON的json解析器庫? – HendraWD
不,我沒有..認爲序列化和反序列化是多個小jsons昂貴的操作...... – Natasha
然後,你應該開始使用其中之一,因爲它會讓你的生活更輕鬆,使你的代碼更好,清潔器。我建議你從FastJSON開始,因爲它是性能方面最好的json解析器(串行器/解串器)。 – HendraWD