Serialization of derived objects with json.net

859 Views Asked by At

Serialization of an object inherited from Dictionary<DateTime, double> does not include field and properties in the resulting json string.

Note: This is a simplified example. Yes, I know one should not derive from the Dictionary type.

Serializing an object of the type:

public class Timeserie : Dictionary<DateTime, double>
{
    public string id;

    public Timeserie()
    {

    }

    public Timeserie(string id)
    {
        this.id = id;
    }
}

Using:

var json_settings = new JsonSerializerSettings() { TypeNameHandling = TypeNameHandling.All };
var s = JsonConvert.SerializeObject(timeserie, Formatting.Indented, json_settings);

Includes only the base class data:

{
  "01/02/2009 00:00:00": 10.23,
  "01/05/2009 00:00:00": 11.33
}

The field id is not included.

How do I need to use json.net so that fields and properties declared in the derived class are included in the serialization?

1

There are 1 best solutions below

8
On

It seems, looking through the code for json.net, it has a special contract for handling dictionaries.

so either make a new contract, or encapsulate the dictionary ( ie, make the dictionary a property of your class )

if you make plain classes that inherit off each other, this code will serialize all the properties of the derived classes