有了JSON.stringify(),处理json将变得更简单!!

时间:2022-10-28 12:17:32
之前处理json 需要拼接json字符串,但是,如果用上JSON.stringify()的话,忘了json语法以没关系了.....
 @{
ViewBag.Title = "GetStr";
} <html>
<head>
<title> </title>
<script type="text/javascript" src="~/Scripts/jquery-1.7.1.min.js"></script>
@* <script type="text/javascript" src="~/Scripts/jquery.jsonp-2.4.0.min.js"></script>*@
<script type="text/javascript"> $(function () {
$("#but").click(function () {
var o = new Object();
o.id = ;
o.name = "张三";
o.age = ;
o.hobby = "玩耍";
var convertStr = JSON.stringify(o);//将js对象转换为json字符串
alert(convertStr);
var array = new Array(,"张三",,"玩耍");
var arryConvertJson = JSON.stringify(array);//把数组转换为json字符串
alert(arryConvertJson);
$.ajax({
url: "/home/getStr",
type: "post",
data: { "convertStr": arryConvertJson },
async: true,
success: function (data) { },
error: function () { },
complete: function () { }
})
})
})
</script>
</head>
<body> <input type="button" id="but" value="提交" />
</body>
</html>

前端处理

  public ActionResult GetStr(string convertStr="")
{ JavaScriptSerializer js = new JavaScriptSerializer();
object[] o=(object[])js.DeserializeObject(convertStr); //将json字符串序列化成数组(json 中为数组)
var ss = o[];
// object p=js.Deserialize(convertStr, typeof(Person));//反序列化成对象
Person p1= js.Deserialize<Person>(convertStr);
return View();
}

后端处理