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
}
}
}