c# - 使用 JSON.Net 序列化数据的问题

标签 c# asp.net-mvc kendo-ui json.net kendo-scheduler

我在应用程序中使用 Kendo Scheduler,通过 Web Api 从数据库中提取数据。我创建了一个 Web Api 函数,并在其中硬编码了一些数据,以确保 Kendo Scheduler 可以读取我的数据。这是我的 Api 函数代码:

    [Route("api/v1/Events/GetPersonalEvents", Name = "ApiEventsGetPersonalEvents")]
    [HttpGet]
    public DataSourceResult GetPersonalEvents([System.Web.Http.ModelBinding.ModelBinder(typeof(WebApiDataSourceRequestModelBinder))]DataSourceRequest request)
    {
        var q = new ViewModels.Events.EventViewModel();
        q.Id = 1;
        q.Title = "This is a test";
        q.Start = DateTime.Now;
        q.End = DateTime.Now.AddHours(1);
        q.Description = "Test entry";

        var list = new List<ViewModels.Events.EventViewModel>();
        list.Add(q);
        return list.ToDataSourceResult(request);
    }

Kendo Scheduler 没有在日历上显示任何内容。使用 Fiddler,我可以看到 Kendo Scheduler 正在调用我的 API,并且我的 API 正在返回数据。以下是发送的 JSON:

{  
   "data":[  
      {  
         "id":1,
         "title":"This is a test",
         "description":"Test entry",
         "isAllDay":false,
         "start":"2016-11-18T15:31:33.1173519-08:00",
         "end":"2016-11-18T16:31:33.1178524-08:00",
         "startTimezone":null,
         "endTimezone":null,
         "recurrenceRule":null,
         "recurrenceException":null
      }
   ],
   "total":1,
   "aggregateResults":null,
   "errors":null
}

一切似乎都运转良好。经过进一步调查,我终于弄清楚了我的问题。在我的 global.asax.cs 文件中,我有以下几行:

HttpConfiguration config = GlobalConfiguration.Configuration;
config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
config.Formatters.JsonFormatter.UseDataContractJsonSerializer = false;

它的作用是让 JSON.Net 自动将 C# 名称转换为 Javascript 友好的名称(例如 Title 变为 titleDescription变成 description 等),这就是我想要的。然而,Kendo 显然要求名称与 C# 类似(例如 Title 而不是 title)。我通过注释掉 global.asax.cs 文件中的这三行来验证这一点,一切正常。

所以,然后我将注意力转向我的 ViewModel。我使用 JsonProperty 属性修饰了我的属性,并指定了特定名称。但是,它仍然被序列化为小写名称。这是 View 模型代码:

public class EventViewModel : ISchedulerEvent
{
    [JsonProperty(PropertyName = "Id")]
    public int Id { get; set; }

    [JsonProperty(PropertyName = "Title")]
    public string Title { get; set; }

    [JsonProperty(PropertyName = "Description")]
    public string Description { get; set; }

    [JsonProperty(PropertyName = "IsAllDay")]
    public bool IsAllDay { get; set; }

    [JsonProperty(PropertyName = "Start")]
    public DateTime Start { get; set; }

    [JsonProperty(PropertyName = "End")]
    public DateTime End { get; set; }

    [JsonProperty(PropertyName = "StartTimezone")]
    public string StartTimezone { get; set; }

    [JsonProperty(PropertyName = "EndTimezone")]
    public string EndTimezone { get; set; }

    [JsonProperty(PropertyName = "RecurrenceRule")]
    public string RecurrenceRule { get; set; }

    [JsonProperty(PropertyName = "RecurrenceException")]
    public string RecurrenceException { get; set; }
}

所以现在我没有主意了。那么有没有一种方法可以让 Json.Net 正确序列化我的名字,只是为了这个方法,或者我可以在 View 模型中使用其他一些属性来使名称正确序列化,或者 Kendo 中是否有一个设置是否允许 Kendo 使用驼峰大小写格式?

最佳答案

如果您使用的是 Json.NET 9.0.1 或更高版本,则可以指定 naming strategy对于特定类型,将其标记为 [JsonObject(NamingStrategyType = typeof(TNamingStrategy))] 。这会覆盖 CamelCasePropertyNamesContractResolver 的命名策略。在你的情况下你想要 DefaultNamingStrategy :

[JsonObject(NamingStrategyType = typeof(DefaultNamingStrategy))]
public class EventViewModel
{
    public int Id { get; set; }

    public string Title { get; set; }

    public string Description { get; set; }

    public bool IsAllDay { get; set; }

    public DateTime Start { get; set; }

    public DateTime End { get; set; }

    public string StartTimezone { get; set; }

    public string EndTimezone { get; set; }

    public string RecurrenceRule { get; set; }

    public string RecurrenceException { get; set; }
}

请注意,不再需要 [JsonProperty("name")] 属性。

在您的全局合约解析器上,还有一个属性 NamingStrategy 。设置NamingStrategy.OverrideSpecifiedNames to false 还可以防止 [JsonProperty("name")] 名称被全局覆盖。对于 CamelCasePropertyNamesContractResolver ,默认值似乎是 true,这就是问题的原因。

关于c# - 使用 JSON.Net 序列化数据的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40687670/

相关文章:

unicode - Kendo UI 窗口不显示西里尔字符

c# - 如果页面最近 5 分钟空闲,如何提示用户

c# - 异常记录中的空引用异常屏蔽真错误

asp.net-mvc - 隐藏和显示字段仍然使用 ASP.NET MVC 2 客户端验证验证隐藏字段

c# - 如何将查询字符串参数转换为asp.net mvc 4中的路由

jquery - ASP.NET MVC 使用带有模型绑定(bind)的 JQuery DatePicker

javascript - 使用网格外部的控件通过远程数据绑定(bind)在 MVC 中过滤 Kendo UI 网格

c# - 在 C# 中检测停滞的 BackgroundWorker

c# - 打开/关闭网络服务

c# - 具有整数值的下拉列表上的 ASP.NET mvc 验证标签?