views:

38

answers:

1

I have a simple class hierachy. Foo is the base class. Bar and Baz are inherited from Foo. Instances of these classes are stored in a List. I have to serialize the list to JSON. It works pretty well. But the problem is deserialising it back into a List<>.

I put Foos, Bars and Bazs in the list, serialize it and when I deserialize it I get only Foos :) I want my Bars and Bazs though. Is that possible with Json.NET?

using System;
using System.Collections.Generic;

using Newtonsoft.Json;

namespace JsonTest
{
  class Foo
  {
    int number;

    public Foo(int number)
    {
      this.number = number;
    }

    public int Number
    {
      get { return number; }
      set { number = value; }
    }
  }

  class Bar : Foo
  {
    string name;

    public Bar(int number, string name)
      : base(number)
    {
      this.name = name;
    }

    public string Name
    {
      get { return name; }
      set { name = value; }
    }
  }

  class Baz : Foo
  {
    float time;

    public Baz(int number, float time)
      : base(number)
    {
      this.time = time;
    }

    public float Time
    {
      get { return time; }
      set { time = value; }
    }
  }

  class Program
  {
    static void Main(string[] args)
    {
      List<Foo> fooList = new List<Foo>();
      fooList.Add(new Foo(123));
      fooList.Add(new Bar(123, "Hello, world"));
      fooList.Add(new Baz(123, 0.123f));

      string json = JsonConvert.SerializeObject(fooList, Formatting.Indented);
      List<Foo> fooList2 = JsonConvert.DeserializeObject<List<Foo>>(json);
      // Now I have only Foos in the List
    }
  }
}
A: 

You are serializing a list of Foos and not a list of Baz and Bars.
I think the simplest solution to keep your logic would be to serialize a list of Baz and Bars and concat the list (this will work only if you can live with a different order).
In generally it does not look natural to work with this design. It would be better to have one class with different constructors and use null when the field is not applicable.

weismat
Hm ... all the fields of Bar and Baz are serialized to JSON though. There is the name field of Bar and the time field of Baz in the JSON after calling JsonConvert.SerializeObject. Only the other way around doesn't work. Deserializing the JSON gives me three Foos. It simply ignores the fields specific to Bar and Baz.I thought there might be a clever trick (like attributes) with Json.NET to keep my class hierarchy.
Fair Dinkum Thinkum