7

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.

Jon Helms
  • 177
  • 10
  • That might not be the best way to do it. I cant get intellisense to see the class properties, though they are there. If the class implements a Dictionary as a property though (ie as a collection class), it works fine. – Ňɏssa Pøngjǣrdenlarp Jun 28 '15 at 12:31
  • The intellisense works fine for me, and I can't use the dictionary as a property because I don't have control over the structure of the json payload. – Jon Helms Jun 28 '15 at 12:46

1 Answers1

8

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

Community
  • 1
  • 1
tzachs
  • 4,331
  • 1
  • 28
  • 28