❶ java後台怎樣獲取前台的json數據
一般是這樣的,先缺枝將對象類型(在js中json就是一個對象),使用json.js(有些瀏覽器支持,有些需要引入)的方法:
JSON.parse(jsonstr); //可伏哪敏以將json字元串緩余轉換成json對象
JSON.stringify(jsonobj); //可以將json對象轉換成json對符串
的第二個轉換成字元串,然後把字元串當作一個參數的值再為其添加一個key然後以key/value的格式將數據傳到後台。
之後後台使用request.getParameter();的方式得到json數據。
❷ java如何返回json格式
例如:
Student st1 = new Student(1, "dg", 18, new Date());
Student st2 = new Student(2, "dg", 18, new Date());
Student st3 = new Student(3, "dg", 18, new Date());
Student st4 = new Student(4, "dg", 18, new Date());
Student st5 = new Student(5, "dg", 18, new Date());
List li = new ArrayList();
JSONObject JO1 = new JSONObject(st1);
JSONObject JO2 = new JSONObject(st2);
JSONObject JO3 = new JSONObject(st3);
JSONObject JO4 = new JSONObject(st4);
JSONObject JO5 = new JSONObject(st5);
li.add(JO1);
li.add(JO2);
li.add(JO3);
li.add(JO4);
li.add(JO5);
JSONArray Ja = new JSONArray(li);
Map ma = new HashMap();
ma.put("Result", "OK");
ma.put("Records", Ja);
JSONObject js = new JSONObject(ma);
out.print(js);
返回結果:
{"Result":"OK","Records":[{"recordDate":"Fri Dec 16 17:54:39 CST 2011","name":"dg","age":18,"personId":1},{"recordDate":"Fri Dec 16 17:54:39 CST 2011","name":"dg","age":18,"personId":2},{"recordDate":"Fri Dec 16 17:54:39 CST 2011","name":"dg","age":18,"personId":3},{"recordDate":"Fri Dec 16 17:54:39 CST 2011","name":"dg","age":18,"personId":4},{"recordDate":"Fri Dec 16 17:54:39 CST 2011","name":"dg","age":18,"personId":5}]}