Jon Helms
Jon Helms

Reputation: 187

Serialize class that inherits dictionary is not serializing properties

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.

Upvotes: 8

Views: 2488

Answers (1)

tzachs
tzachs

Reputation: 5019

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

Upvotes: 9

Related Questions