On the front end:
1. If json is converted from a List object, you can directly traverse json and read the data.
2. If you need to convert the front-end List object into json and pass it to the background, and param is a parameter of ajax, then the conversion is as follows:
var jsonStr = JSON.stringify(list); var param= {}; param.jsonStr=jsonStr; In the background:
1. Convert String to List (convert str to list)
List<T> list = new ArrayList<T>(); JSONArray jsonArray = JSONArray.fromObject(str);//Convert String to json list = JSONArray.toList(jsonArray,t);//The t here is Class<T>
2. Convert List to json
JSONArray json = JSONArray.fromObject(object); String str = json.toString();//Convert json to String
eg:
1. Form a List of Answer objects based on the information entered by the page user
/** * @param answers * @param question_ids * @param types * @return */ private List<Answer> toAnswerList(String[] studentAnswers, 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 < studentAnswers.length; i++) { Answer answer = new Answer(); String studentAnswer = studentAnswers[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; } /** * Convert a json string to list * @param props * @return */ public static List<Answer> convertAnswerFormString(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 to a List of Answer object, which is generated based on the information entered by the user on the client page.
public String getAnswerString(String[] studentAnswers, int[] question_ids, int[] types,int[] scores) { List list = toAnswerList(studenAnswers, question_ids, types, scores); JSONArray jsonarray = JSONArray.fromObject(list); return jsonarray.toString(); }PS: Here are a few more practical json online tools for your reference:
Online JSON code verification, inspection, beautification and formatting tools:
http://tools.VeVB.COM/code/json
JSON online formatting tool:
http://tools.VeVB.COM/code/jsonformat
Online XML/JSON mutual conversion tool:
http://tools.VeVB.COM/code/xmljson
json code online formatting/beautification/compression/editing/converting tools:
http://tools.VeVB.COM/code/jsoncodeformat
Online json compression/escaping tools:
http://tools.VeVB.COM/code/json_yasuo_trans
C language style/HTML/CSS/json code formatting and beautification tools:
http://tools.VeVB.COM/code/ccode_html_css_json