using System.Collections;
using System.Collections.Generic;
using System.Runtime.Serialization.Formatters;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;
public string Foo { get; set; }
public SubObject PropertyA { get; set; }
public class TestConverter1 : JsonConverter
public override bool CanConvert(Type objectType)
return objectType == typeof(RootObject);
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)
var e = (RootObject)value;
writer.WriteStartObject();
JObject o = JObject.FromObject(fi);
o.AddFirst(new JProperty("type", new JValue(fi.GetType().Name)));
writer.WritePropertyName("PropertyA");
public class TestConverter2 : JsonConverter
public override bool CanConvert(Type objectType)
return objectType == typeof(RootObject);
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)
var e = (RootObject)value;
var container = new JObject();
JObject o = JObject.FromObject(fi);
o.AddFirst(new JProperty("type", new JValue(fi.GetType().Name)));
container.Add(new JProperty("PropertyA", o));
container.WriteTo(writer);
public static void Test()
var e = new RootObject { PropertyA = new SubObject { Foo = "foo" } };
var settings1 = new JsonSerializerSettings
Converters = { new TestConverter1() },
var json1 = JsonConvert.SerializeObject(e, Formatting.Indented, settings1);
Console.WriteLine("Serializing {0} with direct writing:", e);
Console.WriteLine(json1);
var settings2 = new JsonSerializerSettings
Converters = { new TestConverter2() },
var json2 = JsonConvert.SerializeObject(e, Formatting.Indented, settings2);
Console.WriteLine("Serializing {0} via JObject:", e);
Console.WriteLine(json1);
public static void Main()
Console.WriteLine("Environment version: " + Environment.Version);
Console.WriteLine("Json.NET version: " + typeof(JsonSerializer).Assembly.FullName);
Console.WriteLine("Failed with unhandled exception: ");
public class AssertionFailedException : System.Exception
public AssertionFailedException() : base() { }
public AssertionFailedException(string s) : base(s) { }
public static class Assert
public static void IsTrue(bool value)
public static void IsTrue(bool value, string message)
throw new AssertionFailedException(message ?? "failed");