0

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.

Will
  • 24,082
  • 14
  • 97
  • 108
dotnetstep
  • 17,065
  • 5
  • 54
  • 72

1 Answers1

0

You clould implement your class like this

public class TestClass : Dictionary<string, object>
{
    public string StudentName
    {
        get { return this["StudentName"] as string; }
        set { this["StudentName"] = value; }
    }

    public string StudentCity
    {
        get { return this["StudentCity"] as string; }
        set { this["StudentCity"] = value; }
    }
}

That way those fixed properties will actually be like helpers for easy access. Notice the way I am setting the value in the dictionary. That way if the key do not exists it will be created and the value assigned to that key otherwise the value will be updated.

Juan M. Elosegui
  • 6,471
  • 5
  • 35
  • 48
  • I got your point. But Still I have question that why Json.net not treat property of class as property to serialize when inherit from Dictionary. I think internally they try to look that if class is type of Dictionary then they just serialize dictionary and ignore other property. – dotnetstep Aug 08 '15 at 04:31
  • FYI look at this answer it seems to be an other way to solve this. http://stackoverflow.com/questions/14893614/json-net-serialize-dictionary-as-part-of-parent-object – Juan M. Elosegui Aug 08 '15 at 04:36
  • Thanks for suggestion. Actually I am bit new to Json.net and I am quite sure that answer will be there as I have common requirement. Also your solution is also nice one which simple but as I try to look around for Json.net I forgot to think about other way around. – dotnetstep Aug 08 '15 at 05:34