标准的发送AJAX到后台的写法如下,这里用jquery来实现的
后台采用的是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>有问题请留言。