【问题标题】:Return multiple objects using Json.Net使用 Json.Net 返回多个对象
【发布时间】:2012-06-03 10:56:17
【问题描述】:

使用内置的 json 转换器,我在我的操作中返回多个对象,如下所示:

return Json(new { success = true, data = units });

当我使用 JSON.NET 库时,我该怎么做?

这显然不能编译:

return new { success = true, data = JsonConvert.SerializeObject(units) };

我不想为此创建一个包含这两个属性的额外视图模型。

我可能对默认的 Json javascript 序列化器有错误的理解吗?

【问题讨论】:

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


    【解决方案1】:

    如果您想使用 Newtonsoft.Json 序列化您的对象,您可以创建一个新的 ActionResult 类并在结果中传递数据。

    例如:

    public class NewtonsoftJsonResult : ContentResult
    {
        private readonly object _data;
    
        public NewtonsoftJsonResult(object data)
        {
            _data = data;
        }
    
        public override void ExecuteResult(ControllerContext context)
        {
            Content = JsonConvert.SerializeObject(_data);
            ContentType = "application/json";
    
            base.ExecuteResult(context);
        }
    }
    

    只需将匿名对象作为数据返回您的自定义 ActionResult:

    public ActionResult Index()
    {
        return new NewtonsoftJsonResult(new { success = true, data = units});
    }
    

    【讨论】:

      【解决方案2】:

      在您的第二个示例中,JsonConvert.SerializeObject(units) 将导致返回给 JavaScript 的字符串。 JavaScript 不会将 data 视为包含一些“真实”数据,而是一个简单的字符串,其中包含大括号。

      像往常一样使用你的第一句话。 MVC 的Json 方法会序列化其中的对象。

      例如:

      class Units
      {
          public int Width { get; set; }
          public int Height { get; set; }
      }
      

      ...

      Units u = new Units { Width = 34, Height = 20 };
      
      return Json(new { success = true, data = units });
      

      将生成一个类似于此的 Json:

      { "success" : "true", "data" : { "Height" : "20", "Width" : "34" } } }
      

      【讨论】:

      • 我不想使用内置的 json 序列化程序。我的问题是关于 Json.net 的,顺便说一下在 javascript 中我这样做: var jsonData = $.parseJSON(data);因此返回一个 json 字符串就可以了。
      猜你喜欢
      • 2015-11-11
      • 1970-01-01
      • 2020-01-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多