2

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?

Sinthia V
  • 2,103
  • 2
  • 18
  • 36
IHMS
  • 71
  • 1
  • 2

1 Answers1

0

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

Keith Nicholas
  • 43,549
  • 15
  • 93
  • 156
  • Both public fields and properties declared in the derived class are ignored. – IHMS Nov 15 '11 at 20:23
  • if you take the inheritance of dictionary out, does it serialize id? – Keith Nicholas Nov 15 '11 at 20:24
  • I basically do exactly what you are doing and it handles subclasses just fine – Keith Nicholas Nov 15 '11 at 20:24
  • Then it behaves as it should. – IHMS Nov 15 '11 at 20:25
  • and if you make a fake base class like MyDictionary { public int fakeProperty { get; set; } and inherit off that, does it still serialize out both the id and fakeproperty? – Keith Nicholas Nov 15 '11 at 20:33
  • One clue maybe that when using running a debugger to view an instance of a timeserie object the fields and properties only appear in the RawData section. – IHMS Nov 15 '11 at 20:38
  • I wrote a fake class that emulates partially Dictionary and JSON works correctly. Hence, there is something about deriving from standard classes that makes this fail. This probably relates to some optimizations that break JSON introspection. Since the amount of pain to implement the IDictionary interface is significant I hope someone finds a work around. I really miss ducks! – IHMS Nov 15 '11 at 20:56
  • Who would agree that .NET type hierarchy is less than ideal because methods in elementary classes such as List and Dictionary are not virtual and one cannot create derived classes from them without worrying about how libraries like JSON work with such classes? – IHMS Nov 15 '11 at 21:15