Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 896
superAl1394 Avatar asked Jul 22 '14 20:07

superAl1394


People also ask

How does the JsonProperty attribute affect JSON serialization?

JsonPropertyAttribute indicates that a property should be serialized when member serialization is set to opt-in. It includes non-public properties in serialization and deserialization. It can be used to customize type name, reference, null, and default value handling for the property value.

Is Newtonsoft JSON obsolete?

Yet Newtonsoft. Json was basically scrapped by Microsoft with the coming of . NET Core 3.0 in favor of its newer offering designed for better performance, System. Text.

What is JsonProperty in C #?

Per the documentation: this is the json key that will be used when serializing/deserializing this object to/from a json string. So, if the value of FileName is file.txt , the serialized result would be { "fileName": "file.txt" }


1 Answers

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().

like image 154
Brian Rogers Avatar answered Oct 17 '22 00:10

Brian Rogers