Far*_*lop 8 asp.net-mvc json asp.net-mvc-4
我有一个动作,它返回一个特定类的对象的JsonResult.我已经使用一些attrib来装饰这个类的属性以避免使用null字段.类定义是:
private class GanttEvent
{
public String name { get; set; }
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public String desc { get; set; }
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public List<GanttValue> values { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
在我的Action中我使用了一个对象
var res = new List<GanttEvent>();
Run Code Online (Sandbox Code Playgroud)
我回来使用:
return Json(res, JsonRequestBehavior.AllowGet);
Run Code Online (Sandbox Code Playgroud)
不幸的是,我仍然在输出时收到空值:
[{"name":"1.1 PREVIOS AL INICIO ","desc":null,"values":null},{"name":"F04-PGA-S10","desc":"Acta preconstrucción","values":null},{"name":"F37-PGA-S10","desc":"Plan de inversión del anticipo","values":null},{"name":"F09-PGA-S10","desc":"Acta de vecindad","values":null},{"name":"F05-PGA-S10","desc":"Acta de inicio","values":null},{"name":"F01-PGA-S10","desc":"Desembolso de anticipo","values":null}]
Run Code Online (Sandbox Code Playgroud)
我错过了什么或做错了什么?
正如Brad Christie所说,MVC4仍然使用JavaScriptSerializer,因此为了让你的对象被Json.Net序列化,你将不得不执行几个步骤.
首先,从JsonResult继承一个新类JsonNetResult,如下所示(基于 此解决方案):
public class JsonNetResult : JsonResult
{
public JsonNetResult()
{
this.ContentType = "application/json";
}
public JsonNetResult(object data, string contentType, Encoding contentEncoding, JsonRequestBehavior jsonRequestBehavior)
{
this.ContentEncoding = contentEncoding;
this.ContentType = !string.IsNullOrWhiteSpace(contentType) ? contentType : "application/json";
this.Data = data;
this.JsonRequestBehavior = jsonRequestBehavior;
}
public override void ExecuteResult(ControllerContext context)
{
if (context == null)
throw new ArgumentNullException("context");
var response = context.HttpContext.Response;
response.ContentType = !String.IsNullOrEmpty(ContentType) ? ContentType : "application/json";
if (ContentEncoding != null)
response.ContentEncoding = ContentEncoding;
if (Data == null)
return;
// If you need special handling, you can call another form of SerializeObject below
var serializedObject = JsonConvert.SerializeObject(Data, Formatting.None);
response.Write(serializedObject);
}
}
Run Code Online (Sandbox Code Playgroud)
然后,在您的控制器中,重写Json方法以使用新类:
protected override JsonResult Json(object data, string contentType, Encoding contentEncoding, JsonRequestBehavior behavior)
{
return new JsonNetResult(data, contentType, contentEncoding, behavior);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7678 次 |
| 最近记录: |