Home > Article > Web Front-end > Conversion between JSON's String string and Java's List object
On the front end:
1. If json is converted from List object, you can directly traverse json and read data.
2. If you need to convert the front-end List object to json and send it to the backend, param is the ajax parameter, then the conversion is as follows:
var jsonStr = JSON.stringify(list); var param= {}; param.jsonStr=jsonStr;
In the backend:
1. Convert String to List (str to list)
List<T> list = new ArrayList<T>(); JSONArray jsonArray = JSONArray.fromObject(str);//把String转换为json list = JSONArray.toList(jsonArray,t);//这里的t是Class<T>
2. Convert List to json
JSONArray json = JSONArray.fromObject(object); String str = json.toString();//把json转换为String
eg:
1. Form a List of Answer objects based on the information input by the page user
/** * @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. Generate a Json string from a List of Answer objects based on the customer Generated from the information input by the user on the end page
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(); }
For more articles related to the mutual conversion of JSON String strings and Java List objects, please pay attention to the PHP Chinese website!