大多数情况下我们返回到客户端的Json有两种方式:
1、直接传对象给Json()去转成Json
代码
public
ActionResult JsonTest()
{
List < Result > list = new List < Result > ();
list.Add( new Result { State = 2 });
list.Add( new Result { State = 5 });
return Json(list,JsonRequestBehavior.AllowGet);
}
{
List < Result > list = new List < Result > ();
list.Add( new Result { State = 2 });
list.Add( new Result { State = 5 });
return Json(list,JsonRequestBehavior.AllowGet);
}
public
ActionResult JsonTest()
{
List < Result > list = new List < Result > ();
list.Add( new Result { State = 2 });
list.Add( new Result { State = 5 });
return Json(list,JsonRequestBehavior.AllowGet);
}
{
List < Result > list = new List < Result > ();
list.Add( new Result { State = 2 });
list.Add( new Result { State = 5 });
return Json(list,JsonRequestBehavior.AllowGet);
}
public
JsonResult JsonTest2()
{
string s = @" [{'State':2},{'State':5}] " ;
return Json(s, JsonRequestBehavior.AllowGet);
}
{
string s = @" [{'State':2},{'State':5}] " ;
return Json(s, JsonRequestBehavior.AllowGet);
}
前端都用同样的方法:
$(
function
() {
$.ajax({
type: " Get " ,
url: " Home/JsonTest " ,
data: { t: new Date() },
dataType: " json " ,
success: function (data) {
alert(data);
}
});
$.ajax({
type: " Get " ,
url: " Home/JsonTest2 " ,
data: { t: new Date() },
dataType: " json " ,
success: function (data) {
alert(data);
}
});
});
$.ajax({
type: " Get " ,
url: " Home/JsonTest " ,
data: { t: new Date() },
dataType: " json " ,
success: function (data) {
alert(data);
}
});
$.ajax({
type: " Get " ,
url: " Home/JsonTest2 " ,
data: { t: new Date() },
dataType: " json " ,
success: function (data) {
alert(data);
}
});
});
这时候得到的结果:
JsonTest : [object Object],[object Object] //已经被转成的Json数组
JsonTest2: [{'State'2},{'State':5}] //还是字符串
第二种情况解决办法到很简单:
alert(eval(
'
(
'
+
data
+
'
)
'
));
运行字符串就可以得到Json数组.
打开reflector查看到JsonResult :
JavaScriptSerializer serializer
=
new
JavaScriptSerializer();
response.Write(serializer.Serialize( this .Data));
response.Write(serializer.Serialize( this .Data));
事实上序列化之后都是string,不知道为什么会这样,不解!! 那位高人指点一二!
解决办法:
原因被重复的Serialize,所以不能用Json()去返回,改用Context就Ok了。
public
ActionResult JsonTest2()
{
string s = @" [{""State"":2},{""State"":5}] " ;
return Content(s);
}
{
string s = @" [{""State"":2},{""State"":5}] " ;
return Content(s);
}