【发布时间】:2014-07-21 08:30:30
【问题描述】:
我已经用 ASP.NET MVC 覆盖了默认的 Json 序列化器:
public class JsonNetResult : JsonResult
{
public JsonNetResult()
{
Settings = new JsonSerializerSettings
{
ReferenceLoopHandling = ReferenceLoopHandling.Error,
};
}
public JsonSerializerSettings Settings { get; private set; }
public override void ExecuteResult(ControllerContext context)
{
if (context == null)
throw new ArgumentNullException("context");
if (this.JsonRequestBehavior == JsonRequestBehavior.DenyGet && string.Equals(context.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase))
throw new InvalidOperationException("JSON GET is not allowed");
HttpResponseBase response = context.HttpContext.Response;
response.ContentType = string.IsNullOrEmpty(this.ContentType) ? "application/json" : this.ContentType;
if (this.ContentEncoding != null)
response.ContentEncoding = this.ContentEncoding;
if (this.Data == null)
return;
var scriptSerializer = JsonSerializer.Create();
using (var sw = new StringWriter())
{
scriptSerializer.Serialize(sw, this.Data);
response.Write(sw.ToString());
}
}
}
当我序列化以下内容时:
public JsonResult GetLevels()
{
List<ListItem> items = new List<ListItem>();
items.Add(new ListItem() { Text = "Home", Value = "5"});
items.Add(new ListItem() { Text = "Live", Value = "6"});
items.Add(new ListItem() { Text = "Dev", Value = "7"});
items.Add(new ListItem() { Text = "Staging", Value = "8"});
return Json(items, JsonRequestBehavior.AllowGet);
}
我得到的 JavaScript 对象如下:
级别:数组[4] 0:“家” 1:“现场” 2:“开发” 3:“分期”
所以在这里我所有的信息都像价值一样丢失了。 但是当我使用 Default Json 序列化程序时,我得到了“正确”的信息序列化
级别: 数组[4]
0:对象 属性:对象 启用:真 选择:假 文字:“家” 值:“5”
1:对象 属性:对象 启用:真 选择:假 文字:《活着》 值:“6” ...
但由于 DateTime 序列化,我需要使用自定义序列化程序。 但我不知道我在自定义 JsonNetResult 上做错了什么或我错过了什么。因为这里有数据丢失或者是不正常的?
【问题讨论】:
-
当我使用 Text 和 Value 创建自己的 .NET Helper 类时,一切正常,但是当我使用 .NET 类 ListItem 时,序列化将不起作用 - 很奇怪
-
我也有同样的问题。你找到答案了吗?
-
嗨,就像我在另一条评论中写的那样 - 我已经编写了自己的 Helper 类 - 然后一切正常。
-
@David 我添加了一个解决方案,以防您仍然感兴趣。
标签: c# asp.net-mvc json serialization