I have one class that contains some fixed properties, and along with that I also have to support a dynamic property which is decided at run time.
My problem is that I want to serialize that class to json
, so I decided to inherit from Dictionary
.
public class TestClass : Dictionary<string,object>
{
public string StudentName { get; set; }
public string StudentCity { get; set; }
}
And I am using it like this:
static void Main(string[] args)
{
TestClass test = new TestClass();
test.StudentCity = "World";
test.StudentName = "Hello";
test.Add("OtherProp", "Value1");
string data = JsonConvert.SerializeObject(test);
Console.WriteLine(data);
Console.ReadLine();
}
My output is like this:
{"OtherProp":"Value1"}
but I expected this:
{"OtherProp":"Value1", "StudentName":"Hello" , "StudentCity":"World"}
As you can see, it does not serialize StudentName
and StudentCity
.
I know that one solution is to add Fix property to dictionary using Reflection or use Json.net it self JObject.FromObject but to do this I have to do manipulation.
I also tried to decorate TestClass
with the JObject
attribute, but it does not produce the desired output.
I don't want to write a custom converter for this as this would be my last option.
Any help or suggestion would be highly appreciated.