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
667 views
in Technique[技术] by (71.8m points)

c# - Newtonsoft JSON for .net is ignoring jsonproperty tags

For some really irritating reason, the JsonProperty tags are not working with Newtonsoft's Json for .net tool. In my class I have these:

    [JsonProperty(PropertyName = "id")]
    public string ID { get; set; }
    [JsonProperty(PropertyName = "title")]
    public string Title { get; set; }
    [JsonProperty(PropertyName = "url")]
    public string Url { get; set; }
    [JsonProperty(PropertyName = "class")]
    public string EventClass { get; set; }
    [JsonProperty(PropertyName = "start")]
    public string Start { get; set; }
    [JsonProperty(PropertyName = "end")]
    public string End { get; set; }

But I am receiving this

{"success":true,
 "result": [{
    "ID":"0",
    "Title":"Eid ul-Fitr",
    "Url":"<blah>",
    "EventClass":"event-info",
    "Start":"1406520000000",
    "End":"1406606400000"},
  etc.

As you can see it is ignoring me setting the property name. I have tried using [System.Runtime.Serialization.DataMember(Name="id")] as well and that has not worked.

Here is what is really driving me up the wall. It worked yesterday. I rolled it back to where it was last night when I committed and it still won't work.

Any thoughts?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Are you sure you're actually serializing using Json.Net? Json(MyClass) is an ASP.NET MVC method. MVC uses the JavaScriptSerializer class, which does not support [JsonProperty] attributes. To use the attributes, you would need to serialize using the Json.Net method JsonConvert.SerializeObject(MyClass). If you want to return that JSON from within an MVC controller then you would need call Content(jsonString, "application/json") instead of Json().


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

1.4m articles

1.4m replys

5 comments

56.9k users

...