Serialize class that inherits dictionary is not serializing properties

前端 未结 1 1232
深忆病人
深忆病人 2021-01-13 01:41

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 p

相关标签:
1条回答
  • 2021-01-13 02:35

    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

    0 讨论(0)
提交回复
热议问题