先看下面的一段代码:
public class UserTest
{
public int age { set; get; }
public string name { set; get; } }
这是准备 json序列化的类,用mvc框架提供的json方法,很快就可以完成,代码如下:
public ActionResult TestAjax(int? page)
{
UserTest test = new UserTest() { age = 20, name = "aa" };
return Json(test)
}
现在问题是要控制序列化的属性,比如说想让name序列化,age不序列化,如何做到。
NonSerialized和XmlIgnore都不可以。又试了下用[DataContract]也不可以,突然想到为什么不看看json实现的源码了,打开mvc框架源码,找到json方法的源码如下:
public override void ExecuteResult(ControllerContext context) {
if (context == null) {
throw new ArgumentNullException("context");
}
HttpResponseBase response = context.HttpContext.Response;
if (!String.IsNullOrEmpty(ContentType)) {
response.ContentType = ContentType;
}
else {
response.ContentType = "application/json";
}
if (ContentEncoding != null) {
response.ContentEncoding = ContentEncoding;
}
if (Data != null) {
// The JavaScriptSerializer type was marked as obsolete prior to .NET Framework 3.5 SP1
#pragma warning disable 0618
JavaScriptSerializer serializer = new JavaScriptSerializer();
response.Write(serializer.Serialize(Data));
#pragma warning restore 0618
}
}
看到了吧,原来json底层还是用 JavaScriptSerializer实现的,而 JavaScriptSerializer在。net 3.5是已被标示为obsolete,看到这里,豁然开朗,将不需要序列化的属性标上 [ScriptIgnore]即可。至此,问题解决。