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

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; }

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);
}

Tags:

C#

Json

Json.Net