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

标准的发送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","name":"spot1"},{"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>

有问题请留言。




  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值