46

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?

robert
  • 8,459
  • 9
  • 45
  • 70
  • Not a duplicate. This question seeks to solve a specific and distinct problem. One that I had, by the way, so I'm kind of invested in this. – MrBoJangles Aug 11 '15 at 16:14

4 Answers4

99

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; }
Jerry
  • 4,507
  • 9
  • 50
  • 79
27

You can achieve this by using DataContractJsonSerializer

[DataContract]
public class Item
{
    [DataMember(Name = "id")]
    public int Id { get; set; }
    [DataMember(Name = "name")]
    public string Name { get; set; }
    [DataMember(Name = "count")]
    public int Count { get; set; }
}

[DataContract]
public class ItemCollection
{
    [DataMember(Name = "veg")]
    public IEnumerable<Item> Vegetables { get; set; }
    [DataMember(Name = "non-veg")]
    public IEnumerable<Item> NonVegetables { get; set; }
}

now you can deserialize it with something like this:

string data;

// fill the json in data variable

ItemCollection collection;
using (MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(data)))
{
    DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(ItemCollection));
    collection = (ItemCollection)serializer.ReadObject(ms);
}
Vasil Trifonov
  • 1,857
  • 16
  • 21
1

Based on Jerry's answer you can do it this way using System.Text.Json.Serialization:

[JsonPropertyName("non-veg")]
public string nonVeg { get; set; }
Iván Sainz
  • 409
  • 6
  • 12
0

You can use JObject.Parse (included in newtonsoft) to grab any properties even if they have special characters.

JObject result = JObject.Parse(json);
Console.WriteLine(result["non-veg"][0]["name"].ToString());
Wes
  • 1,847
  • 1
  • 16
  • 30