JSON的String字符串與Java的List列表對象的互相轉換。本站提示廣大學習愛好者:(JSON的String字符串與Java的List列表對象的互相轉換)文章只能為提供參考,不一定能成為您想要的結果。以下是JSON的String字符串與Java的List列表對象的互相轉換正文
在前端:
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(); }