using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Globalization;
using System.Collections.Specialized;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;
[JsonConverter(typeof(TestConverter))]
public string Value { get; set; }
public class TestConverter : JsonConverter
public static readonly DataType someSpecialDataTypeInstance = new DataType { Value = "SingleTon" };
public override bool CanConvert(Type objectType)
throw new NotImplementedException();
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
if (reader.Value != null && reader.ValueType == typeof(string))
return someSpecialDataTypeInstance;
else if (reader.TokenType == JsonToken.StartObject)
existingValue = existingValue ?? serializer.ContractResolver.ResolveContract(objectType).DefaultCreator();
serializer.Populate(reader, existingValue);
else if (reader.TokenType == JsonToken.Null)
throw new JsonSerializationException();
public override bool CanWrite { get { return false; } }
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
throw new NotImplementedException();
public DataType DataType { get; set; }
public string ZZValue { get; set; }
public static void Test()
var test = new TestClass { DataType = new DataType { Value = "Foo Bar" }, ZZValue = "value that comes after the DataType and must be successfully deserialized." };
var json = JsonConvert.SerializeObject(test, Formatting.Indented);
Console.WriteLine("JSON with object value for DataType: ");
var test2 = JsonConvert.DeserializeObject<TestClass>(json);
if (test2.DataType.Value != test.DataType.Value)
throw new InvalidOperationException();
if (test2.ZZValue != test.ZZValue)
throw new InvalidOperationException();
Console.WriteLine("JSON was successfully deserialized.");
var token = JToken.Parse(json);
token["DataType"] = (JValue)"hello";
var json3 = token.ToString();
Console.WriteLine("JSON with string value for DataType: ");
Console.WriteLine(json3);
var test3 = JsonConvert.DeserializeObject<TestClass>(json3);
if (test3.DataType != TestConverter.someSpecialDataTypeInstance)
throw new InvalidOperationException();
if (test3.ZZValue != test.ZZValue)
throw new InvalidOperationException();
Console.WriteLine("JSON was successfully deserialized.");
public static void Main()
Console.WriteLine("Json.NET version: " + typeof(JsonSerializer).Assembly.FullName + "\n");
Console.WriteLine("Test of TestConverter failed. Exception: ");