Question35586987 json-net-custom-serialization-with-jsonconverter-how-to-get-the-default-beha

CSharp · Console

/Program.cs

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Threading;
using System.Collections.ObjectModel;
using System.Reflection;
using System.ComponentModel;
using System.Globalization;
using System.Collections.Specialized;

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;

    [JsonConverter(typeof(TestConverter))]
    public class DataType
    {
        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);
                return existingValue;
            }
            else if (reader.TokenType == JsonToken.Null)
            {
                return null;
            }
            else
            {
                throw new JsonSerializationException();
            }
        }

        public override bool CanWrite { get { return false; } }

        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            throw new NotImplementedException();
        }
    }

    public class TestClass
    {
        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: ");
            Console.WriteLine(json);
            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 class Program
	{
		public static void Main()
		{
            Console.WriteLine("Json.NET version: " + typeof(JsonSerializer).Assembly.FullName + "\n");
			
			try
			{
				TestClass.Test();
			}
			catch (Exception ex)
			{
				Console.WriteLine("Test of TestConverter failed.  Exception: ");
				Console.WriteLine(ex);
				throw;
			}
		}
	}
;