-->

Issue with serializing data using JSON.Net

2019-03-02 04:10发布

问题:

I am using a Kendo Scheduler in my app to pull data from my database using a Web Api. I created a Web Api function and just hard coded some data in there to be sure the Kendo Scheduler could read my data. Here is my code for the Api function:

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

The Kendo Scheduler was not showing anything on the calendar. Using Fiddler, I was able to see that Kendo Scheduler was calling my API and my API was returning data. Here is the JSON getting sent:

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

Everything seemed to be working fine. Upon further investigation, I finally figured out my issue. In my global.asax.cs file I have these lines:

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

What this does is it causes JSON.Net to automatically convert C# names to Javascript-friendly names (e.g. Title becomes title, Description becomes description, etc...), which is what I want. However, Kendo, apparently, requires the names to be like C# (e.g. Title instead of title). I verified this by commenting out those three lines in my global.asax.cs file and everything worked fine.

So, then I turned my attention to my ViewModel. I decorated my properties with the JsonProperty attribute, specifying a specific name. However, it's still being serialized as lower case names. Here is the view model code:

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

So now I am out of ideas. So is there a way to either a way to make Json.Net serialize my names properly JUST for this one method or is there some other attribute I can use in my view model to make the names serialize correctly or is there a setting in Kendo that would allow Kendo to use the camel case format?

回答1:

If you are using Json.NET 9.0.1 or later, you can specify a 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; }
}

Note that the [JsonProperty("name")] attributes are no longer needed.

On your global contract resolver, there is also a property NamingStrategy. Setting NamingStrategy.OverrideSpecifiedNames to false also prevents [JsonProperty("name")] names from being overridden globally. For CamelCasePropertyNamesContractResolver it seems the default is true, which is the cause of your problem.