using System.Collections.Generic;
using Newtonsoft.Json.Serialization;
using Newtonsoft.Json.Linq;
public static void Main(string[] args)
Zoo hardcodedZoo = new Zoo()
Animals = new List<IAnimal>
Children = new List<IAnimal>
JsonSerializerSettings settings = new JsonSerializerSettings()
ContractResolver = new CamelCasePropertyNamesContractResolver(),
Formatting = Formatting.Indented
settings.Converters.Add(new AnimalsConverter());
string json = JsonConvert.SerializeObject(hardcodedZoo, settings);
public string Name { get; set; }
public List<IAnimal> Animals { get; set; }
string Name { get; set; }
List<IAnimal> Children { get; set; }
public class Cat : IAnimal
public string Name { get; set; }
public List<IAnimal> Children { get; set; }
Children = new List<IAnimal>();
public Cat(string name = "") : this()
public class Dog : IAnimal
public string Name { get; set; }
public List<IAnimal> Children { get; set; }
Children = new List<IAnimal>();
public Dog(string name = "") : this()
class AnimalsConverter : JsonConverter
public override bool CanConvert(Type objectType)
return (typeof(IAnimal).IsAssignableFrom(objectType));
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
throw new NotImplementedException();
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
JObject jo = new JObject();
Type type = value.GetType();
jo.Add("type", type.Name);
foreach (PropertyInfo prop in type.GetProperties())
object propVal = prop.GetValue(value, null);
jo.Add(prop.Name, JToken.FromObject(propVal, serializer));