在前端:
1.如果json是List對象轉換的,可以直接遍歷json,讀取數據。
2.如果是需要把前端的List對象轉換為json傳到后臺,param是ajax的參數,那么轉換如下所示:
var jsonStr = JSON.stringify(list); var param= {}; param.jsonStr=jsonStr; 在后臺:
1.把String轉換為List(str轉換為list)
List<T> list = new ArrayList<T>(); JSONArray jsonArray = JSONArray.fromObject(str);//把String轉換為json list = JSONArray.toList(jsonArray,t);//這里的t是Class<T>
2.把List轉換為json
JSONArray json = JSONArray.fromObject(object); String str = json.toString();//把json轉換為String
eg:
1. 根據頁面用戶輸入的信息形成 Answer 對象的List
/** * @param answers * @param question_ids * @param types * @return */ private List<Answer> toAnswerList(String[] studenAnswers, int[] question_ids, int[] types,int[] scores) { List<Answer> answerList = new ArrayList<Answer>(); if(studenAnswers!=null && question_ids!= null && types!= null&& scores!= null){ for (int i = 0; i < studenAnswers.length; i++) { Answer answer = new Answer(); String studenAnswer = studenAnswers[i]; int type = types[i]; int question_id = question_ids[i]; int score = scores[i]; answer.setQuestion_id(question_id); answer.setScore(score); answer.setStudenAnswer(studenAnswer); answer.setType(type); answerList.add(answer); } } return answerList; } /** * 將一個json字串轉為list * @param props * @return */ public static List<Answer> converAnswerFormString(String answer){ if (answer == null || answer.equals("")) return new ArrayList(); JSONArray jsonArray = JSONArray.fromObject(answer); List<Answer> list = (List) JSONArray.toCollection(jsonArray, Answer.class); return list; } 2. 將一個 Answer 對象的List 生成Json字串,是根據客戶端頁面用戶輸入的信息生成的
public String getAnswerString(String[] studenAnswers, int[] question_ids, int[] types,int[] scores) { List list = toAnswerList(studenAnswers, question_ids, types, scores); JSONArray jsonarray = JSONArray.fromObject(list); return jsonarray.toString(); }
PS:這里再為大家推薦幾款比較實用的json在線工具供大家參考使用:
在線JSON代碼檢驗、檢驗、美化、格式化工具:
http://tools.VeVB.COm/code/json
JSON在線格式化工具:
http://tools.VeVB.COm/code/jsonformat
在線XML/JSON互相轉換工具:
http://tools.VeVB.COm/code/xmljson
json代碼在線格式化/美化/壓縮/編輯/轉換工具:
http://tools.VeVB.COm/code/jsoncodeformat
在線json壓縮/轉義工具:
http://tools.VeVB.COm/code/json_yasuo_trans
C語言風格/HTML/CSS/json代碼格式化美化工具:
http://tools.VeVB.COm/code/ccode_html_css_json
新聞熱點
疑難解答