CSharp · Console
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using Newtonsoft.Json.Linq;
using System.Reflection;
public class Program
{
public static void Main(string[] args)
{
Zoo hardcodedZoo = new Zoo()
{
Name = "My Zoo",
Animals = new List<IAnimal>
{
new Dog("Ruff"),
new Cat("Cleo"),
new Dog("Rover")
{
Children = new List<IAnimal>
{
new Dog("Fido"),
new Dog("Fluffy")
}
}
}
};
JsonSerializerSettings settings = new JsonSerializerSettings()
{
ContractResolver = new CamelCasePropertyNamesContractResolver(),
Formatting = Formatting.Indented
};
settings.Converters.Add(new AnimalsConverter());
string json = JsonConvert.SerializeObject(hardcodedZoo, settings);
Console.Write(json);
}
}
class Zoo
{
public string Name { get; set; }
public List<IAnimal> Animals { get; set; }
}
public interface IAnimal
{
string Name { get; set; }
string Speak();
List<IAnimal> Children { get; set; }
}
public class Cat : IAnimal
{
public string Name { get; set; }
public List<IAnimal> Children { get; set; }
public Cat()
{
Children = new List<IAnimal>();
}
public Cat(string name = "") : this()
{
Name = name;
}
public string Speak()
{
return "Meow";
}
}
public class Dog : IAnimal
{
public string Name { get; set; }
public List<IAnimal> Children { get; set; }
public Dog()
{
Children = new List<IAnimal>();
}
public Dog(string name = "") : this()
{
Name = name;
}
public string Speak()
{
return "Arf";
}
}
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())
{
if (prop.CanRead)
{
object propVal = prop.GetValue(value, null);
if (propVal != null)
{
jo.Add(prop.Name, JToken.FromObject(propVal, serializer));
}
}
}
jo.WriteTo(writer);
}
}