JSON Serialization with class inheritance from dictionary <T, V>
I have a class that is currently inheriting from a dictionary, and then adds several properties of the first class class to it. Roughly speaking:
public class Foo : Dictionary<string, string> { public string Bar { get; set; } public string Baz { get; set; } } After serializing the instance of this object in JSON, however, it seems that the serializer only emits the key / value pairs that I saved in the dictionary. Even if I apply the DataMember attributes to the new properties of the first class, the JSON serializer does not seem to know what to do with them, but instead simply ignores them.
I assume that there is something fundamentally elementary that I am missing, but looking through code samples and documents on the JSON .net serializer, I found only trivial examples that do not quite correspond to what I am doing. All our other classes that come from some other base class do not seem to exhibit this problem, this is one that follows from a general vocabulary, in particular that gives us seizures.
[Change] If you do not move the dictionary to Foo as a property of the first class, is there a way to make this work? I assume the hang is that the serializer does not know what to βnameβ the dictionary to distinguish it from other members?
Perhaps in this case it would be better to use a solution based on composition:
using System; using System.Collections.Generic; using System.Runtime.Serialization.Json; using System.IO; using System.Text; class Program { static void Main() { Foo foo = new Foo { Bar = "bar", Baz = "baz" }; foo.Items.Add("first", "first"); DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(Foo)); using (MemoryStream ms = new MemoryStream()) { serializer.WriteObject(ms, foo); Console.WriteLine(Encoding.Default.GetString(ms.ToArray())); } } } public class Foo { public Dictionary<string, string> Items { get; set; } public string Bar { get; set; } public string Baz { get; set; } public Foo() { this.Items = new Dictionary<string, string>(); } } Produces this conclusion:
{"Bar":"bar","Baz":"baz","Items":[{"Key":"first","Value":"first"}]}
Would this solve your problem as a workaround?