标准的发送AJAX到后台的写法如下,这里用jquery来实现的
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",{"ath":"-75.014","atv":"8.862","linkedscene":"scene_img_3773_panorama","name":"spot2"}]}}];
$.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); } })
后台采用的是spring mvc来接收的,后台接收的方式也分为了两种,一种是用@RequestBody来处理的,一种是用common io的工具类IoUtils来读取二进制流将其解析成一个字符串,之后再用fastjson来将一个Json字符串转成java对象
@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){ 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; } }
另外将spring.xml部分对json的配置分享出供大家来查阅,spring对json的配置交给了fastjson来处理,配置如下
<mvc:annotation-driven> <!-- 编码转换 --> <mvc:message-converters register-defaults="true"> <bean class="org.springframework.http.converter.StringHttpMessageConverter"> <property name="supportedMediaTypes"> <list> <value>text/plain;charset=UTF-8</value> <value>text/html;charset=UTF-8</value> <value>application/json;charset=UTF-8</value> </list> </property> </bean> <!-- 将spring的json处理交给fastjson --> <bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter"> <property name="supportedMediaTypes" value="application/json;charset=UTF-8"/> <property name="features"> <list> <value>WriteMapNullValue</value> <value>QuoteFieldNames</value> </list> </property> </bean> </mvc:message-converters> </mvc:annotation-driven>有问题请留言。 原文链接:https://www.f2er.com/ajax/161836.html