0%

有关用AJAX发送JSON数据到后台的问题总结

1.数据有对象,有list
数据1:

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
var xml_data = [{
"name": "scene_img_3773_panorama",
"sceneAttr": {
"view": {
"hlookat": "1.008",
"vlookat": "-4.579"
},
"hotspots": [{
"ath": "-4.124",
"atv": "4.146",
"linkedscene": "scene_img_7994_panorama",
"name": "spot1"
},
{
"ath": "-4.124",
"atv": "8.146",
"name": "spot2"
}
]
}
},
{
"name": "scene_img_7994_panorama",
"secenAttr": {
"view": {
"hlookat": "-3.296",
"vlookat": "2.283"
},
"hotspots": [{
"ath": "-19.613",
"atv": "11.459",
"linkedscene": "scene_img_7984_panorama",
"name": "spot1"
},
{
"ath": "-75.014",
"atv": "8.862",
"linkedscene": "scene_img_3773_panorama",
"name": "spot2"
}
]
}
}
]

数据2:

1
var json={ "addr_num":"runoob", "user_guid":10000};

2.ajax调用

1
2
3
4
5
6
7
8
9
10
11
$.ajax({
type: ”POST”,
url: ” /panorama/saveScene”,
processData: false,
contentType: “application / json;charset = utf - 8”, //这个是发送信息至服务器时内容编码类型
dataType: “json”,
data: JSON.stringify(xml_data), //这里必须将对象转成string类型,否则将掉入无线的大坑中。。。
success: function(msg) {
alert(msg);
}
});

3.后台采用的是spring mvc来接收的,后台接收的方式也分为了两种,一种是用@RequestBody来处理的,一种是用common io的工具类IOUtils来读取二进制流将其解析成一个字符串,之后再用fastjson来将一个Json字符串转成java对象

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
@Controller  
@RequestMapping(“/panorama”)
public class PanoController extends BaseController {
/**
* 用@RequestBody的方式来将json反序列化成list<Scene>对象
* @param scene
* @return
*/
@RequestMapping(value = “saveScene”,method = RequestMethod.POST)
@ResponseBody
public List<Scene> saveScene(@RequestBody List<Scene> scene,或者是对象,@RequestBody Address user){
System.out.println(“JSONTOJAVAOBJ===================”+scene.size());
return scene;
}
//io流读取二进制json对象
public List<Scene> saveScene(HttpServletRequest request) throws IOException{
String jsonStr = IOUtils.toString(request.getInputStream(),”UTF-8″);
System.out.println(“JSONTOJAVAOBJ============”+JSON.parseObject(jsonStr,new TypeReference<List<Scene>>(){}));
return null;
}
}