详解springmvc之json数据交互controller方法返回值为简单类型
当controller方法的返回值为简单类型比如String时,该如何与json交互呢?
使用@RequestBody
比如代码如下:
@RequestMapping(value="/ceshijson",produces="application/json;charset=UTF-8")
@ResponseBody
publicStringceshijson(@RequestBodyStringchannelId)throwsIOException{
returnchannelId;
如果代码为上面这种情况时,前台发送json时,应该这样写(写法有很多,能用就行)
functionchannel(){
//先获取选中的值
varchannelId=$("#channelIdoption:selected").val();
//来判断发送的链接
if(channelId==2){
$.ajax({
url:"ceshijson",
type:"post",
dataType:'json',
contentType:'application/json;charset=utf-8',
data:JSON.stringify({'channelId':channelId}),
success:function(data){
alert(data.channelId);
},
error:function(XMLHttpRequest,textStatus,errorThrown){
alert("Error")
alert(XMLHttpRequest.status);
alert(XMLHttpRequest.readyState);
alert(textStatus);
}
});
}
}
这里需要特别注意:上篇也强调过,使用了@RequestBody时,它要求StringchannelId接收到数据为json字符串。也就是要是data写成这样:data:{‘channelId':channelId},就是错误的。因为这是json对象形式。
要是你不想使用JSON.stringify()这个函数,那就自己手动字符串拼接:
data:'{"channelId":'+channelId+'}'
这里还要注意channelId是双引号,不能写成单引号,因为这是json语法规则。你改成单引号,也就是
**错误写法
data:"{'channelId':"+channelId+"}"
这种形式,虽然可以传给后台,但是后台传回来的会出现undefined。也就是key必须要用双引号包围。
不使用@RequestBody
@RequestMapping(value="/ceshijson",produces="application/json;charset=UTF-8")
@ResponseBody
publicStringceshijson(StringchannelId)throwsIOException{
Mapmap=newHashMap();
map.put("channelId",channelId);
ObjectMappermapper=newObjectMapper();
channelId=mapper.writeValueAsString(map);
returnchannelId;
}
前台代码
$.ajax({
url:"ceshijson",
type:"post",
dataType:'json',
//contentType:'application/json;charset=utf-8',
data:"channelId="+channelId,
success:function(data){
alert(data);
},
error:function(XMLHttpRequest,textStatus,errorThrown){
alert("Error")
alert(XMLHttpRequest.status);
alert(XMLHttpRequest.readyState);
alert(textStatus);
}
});
这种方式利用ObjectMapper中的writeValueAsString将Java对象转换为json字符串。
总结:这种方式,其实是没有多大的实际意思,因为一般接收数据不是这么接收的。只做了解!
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。