Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
240 views
in Technique[技术] by (71.8m points)

c# - Issue with serializing data using JSON.Net

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...