Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to deserialize a property with a dash (“-”) in it's name with NewtonSoft JsonConvert?

Tags:

json

c#

json.net

We have a JSON object with one of the object having a dash in its name. Ex below.

{     "veg": [         {             "id": "3",             "name": "Vegetables",             "count": "25"         },         {             "id": "4",             "name": "Dal",             "count": "2"         },         {             "id": "5",             "name": "Rice",             "count": "8"         },         {             "id": "7",             "name": "Breads",             "count": "6"         },         {             "id": "9",             "name": "Meals",             "count": "3"         },         {             "id": "46",             "name": "Extras",             "count": "10"         }     ],     "non-veg": [         {             "id": "25",             "name": "Starters",             "count": "9"         },         {             "id": "30",             "name": "Gravies",             "count": "13"         },         {             "id": "50",             "name": "Rice",             "count": "4"         }     ] } 

How can we deserialize this json?

like image 285
robert Avatar asked Feb 07 '13 14:02

robert


People also ask

How does Newtonsoft JSON deserialize work?

Newtonsoft. Json uses reflection to get constructor parameters and then tries to find closest match by name of these constructor parameters to object's properties. It also checks type of property and parameters to match. If there is no match found, then default value will be passed to this parameterized constructor.

What does JsonConvert return?

Return ValueThe deserialized object from the JSON string.

What is JsonConvert?

Provides methods for converting between . NET types and JSON types.


1 Answers

To answer the question on how to do this WITH NewtonSoft, you would use the JsonProperty property attribute flag.

[JsonProperty(PropertyName="non-veg")] public string nonVeg { get; set; } 
like image 65
Jerry Avatar answered Sep 22 '22 11:09

Jerry