在前端:
1.如果json是List對(duì)象轉(zhuǎn)換的,可以直接遍歷json,讀取數(shù)據(jù)。
2.如果是需要把前端的List對(duì)象轉(zhuǎn)換為json傳到后臺(tái),param是ajax的參數(shù),那么轉(zhuǎn)換如下所示:
1
2
3
|
var jsonStr = JSON.stringify(list); var param= {}; param.jsonStr=jsonStr; |
在后臺(tái):
1.把String轉(zhuǎn)換為L(zhǎng)ist(str轉(zhuǎn)換為list)
1
2
3
|
List<T> list = new ArrayList<T>(); JSONArray jsonArray = JSONArray.fromObject(str); //把String轉(zhuǎn)換為json list = JSONArray.toList(jsonArray,t); //這里的t是Class<T> |
2.把List轉(zhuǎn)換為json
1
2
|
JSONArray json = JSONArray.fromObject(object); String str = json.toString(); //把json轉(zhuǎn)換為String |
eg:
1. 根據(jù)頁(yè)面用戶輸入的信息形成 Answer 對(duì)象的List
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
|
/** * @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; } /** * 將一個(gè)json字串轉(zhuǎn)為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. 將一個(gè) Answer 對(duì)象的List 生成Json字串,是根據(jù)客戶端頁(yè)面用戶輸入的信息生成的
1
2
3
4
5
6
7
8
|
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(); } |