在前端:
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
refreee
.產生Json字符串,是根據客戶端頁面使用者輸入的資訊產生的/** * @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; }更多JSON的String字串與Java的List列表物件的相互轉換相關文章請關注PHP中文網!