【问题标题】:MVC4 Action returning JsonResult without nullMVC4 动作返回 JsonResult 而没有 null
【发布时间】:2012-11-08 17:16:27
【问题描述】:

我有一个为特定类的对象返回 JsonResult 的操作。我用一些属性修饰了这个类的属性以避免空字段。类定义为:

    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; }
    }

在我的行动中,我使用了一个对象

    var res = new List<GanttEvent>();

我使用返回的:

    return Json(res, JsonRequestBehavior.AllowGet);

不幸的是,我仍然在输出中收到空值:

    [{"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}]

我是否遗漏了什么或做错了什么?

【问题讨论】:

    标签: asp.net-mvc json asp.net-mvc-4


    【解决方案1】:

    正如 Brad Christie 所说,MVC4 Stills 使用 JavaScriptSerializer,因此为了让您的对象被 Json.Net 序列化,您必须执行几个步骤。

    首先,从JsonResult继承一个新的类JsonNetResult如下(基于this solution):

    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);
        }
    }
    

    然后,在您的控制器中,重写 Json 方法以使用新类:

    protected override JsonResult Json(object data, string contentType, Encoding contentEncoding, JsonRequestBehavior behavior)
    {
        return new JsonNetResult(data, contentType, contentEncoding, behavior);
    }
    

    【讨论】:

    • 不知道这个答案是否仍然相关,但我需要这样的东西,并对你的代码做了一个 c/p。不幸的是,它没有按预期工作,但我稍微编辑了您的 JsonNetResult 类: var serializedObject = JsonConvert.SerializeObject(Data, Formatting.None, new JsonSerializerSettings{ NullValueHandling = NullValueHandling.Ignore}); ...现在它完美地工作了。谢谢!
    【解决方案2】:

    Controller.Json 使用 JavaScriptSerializer 而不是 Newtonsoft Json library(这是 JsonPropertyAttribute 的来源)。

    您要么需要使用 Newtonsoft 库并以这种方式返回序列化结果,要么继续调用 Json 并编写将忽略空值的 converter

    【讨论】:

    • 谢谢,我对此表示怀疑,您证实了我的想法。最后,Json.Net 是默认的序列化器,但仅适用于 WebAPI,不适用于常规 MVC 站点。
    【解决方案3】:

    我的建议是看看如果你只是将一个 GanttEvent 对象序列化为 JSON 会发生什么。还要检查您对 Json 的调用是否合适。

    【讨论】:

      猜你喜欢
      • 2014-05-17
      • 2014-10-14
      • 1970-01-01
      • 2019-08-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-10
      • 1970-01-01
      相关资源
      最近更新 更多