I have a class that inherits from Dictionary and has a couple of properties on it. When I serialize it only serializes the dictionary and not the properties. If I have a payload that includes the properties it does deserialize to them. How can I make it serialize my object including the properties?
public class Maintenance : Dictionary<string, dynamic>
{
public int PersonId { get; set; }
}
return JsonConvert.DeserializeObject<T>(jsonString); //Populates PersonId and all other properties end up in the dictionary.
return JsonConvert.SerializeObject(maintenance); //Only returns dictionary contents
I'd appreciate suggestions on how to make serialization use the same behavior as deserialization seems to use.
From Json.Net documentation: "Note that only the dictionary name/values will be written to the JSON object when serializing, and properties on the JSON object will be added to the dictionary's name/values when deserializing. Additional members on the .NET dictionary are ignored during serialization."
Taken from this link: http://www.newtonsoft.com/json/help/html/SerializationGuide.htm
Assuming you want the keys & values of the dictionary on the same hierarchy level as PersonId in the json output, you can use the JsonExtensionData
attribute with composition instead of inheritance, like this:
public class Maintenance
{
public int PersonId { get; set; }
[JsonExtensionData]
public Dictionary<string, dynamic> ThisNameWillNotBeInTheJson { get; set; }
}
Also look at this question: How to serialize a Dictionary as part of its parent object using Json.Net
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With