使用 JSON.Net 序列化数据时出现问题

Issue with serializing data using JSON.Net

我在我的应用程序中使用 Kendo 调度程序,通过 Web Api 从我的数据库中提取数据。我创建了一个 Web Api 函数,并在其中硬编码了一些数据,以确保 Kendo 调度程序可以读取我的数据。这是我的 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 日程安排程序未在日历上显示任何内容。使用 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 属性装饰了我的属性,指定了一个特定的名称。但是,它仍然被序列化为小写名称。这是视图模型代码:

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 正确地序列化我的名字只是为了这个方法,或者是否有一些其他属性我可以在我的视图模型中使用来使名字正确序列化或者是否有一个设置Kendo 允许 Kendo 使用驼峰格式?

如果您使用的是 Json.NET 9.0.1 或更高版本,您可以指定 naming strategy for a specific type by marking it with [JsonObject(NamingStrategyType = typeof(TNamingStrategy))]. This overrides the naming strategy of CamelCasePropertyNamesContractResolver. In your case you want 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. Setting NamingStrategy.OverrideSpecifiedNamesfalse 也可以防止 [JsonProperty("name")] 名称被全局覆盖。对于 CamelCasePropertyNamesContractResolver,默认值似乎是 true,这就是您遇到问题的原因。