Question38336390 serialize untyped dictionary and preserve primitive types

CSharp · Console

/Program.cs

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.IO;
using System.Reflection;

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

    public class UntypedToTypedValueContractResolver : DefaultContractResolver
    {
        // As of 7.0.1, Json.NET suggests using a static instance for "stateless" contract resolvers, for performance reasons.
        // http://www.newtonsoft.com/json/help/html/ContractResolver.htm
        // http://www.newtonsoft.com/json/help/html/M_Newtonsoft_Json_Serialization_DefaultContractResolver__ctor_1.htm
        // "Use the parameterless constructor and cache instances of the contract resolver within your application for optimal performance."
        // See also https://stackoverflow.com/questions/33557737/does-json-net-cache-types-serialization-information
        static UntypedToTypedValueContractResolver instance;

        // Explicit static constructor to tell C# compiler not to mark type as beforefieldinit
        static UntypedToTypedValueContractResolver() { instance = new UntypedToTypedValueContractResolver(); }

        public static UntypedToTypedValueContractResolver Instance { get { return instance; } }

        protected override JsonDictionaryContract CreateDictionaryContract(Type objectType)
        {
            var contract = base.CreateDictionaryContract(objectType);

            if (contract.DictionaryValueType == typeof(object) && contract.ItemConverter == null)
            {
                contract.ItemConverter = new UntypedToTypedValueConverter();
            }

            return contract;
        }
    }

    class UntypedToTypedValueConverter : JsonConverter
    {
        public override bool CanConvert(Type objectType)
        {
            throw new NotImplementedException("This converter should only be applied directly via ItemConverterType, not added to JsonSerializer.Converters");
        }

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            if (reader.TokenType == JsonToken.Null)
                return null;
            var value = serializer.Deserialize(reader, objectType);
            if (value is TypeWrapper)
            {
                return ((TypeWrapper)value).ObjectValue;
            }
            return value;
        }

        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            if (serializer.TypeNameHandling == TypeNameHandling.None)
            {
                Console.WriteLine("ObjectItemConverter used when serializer.TypeNameHandling == TypeNameHandling.None");
                serializer.Serialize(writer, value);
            }
            // Handle a couple of simple primitive cases where a type wrapper is not needed
            else if (value is string)
            {
                writer.WriteValue((string)value);
            }
            else if (value is bool)
            {
                writer.WriteValue((bool)value);
            }
            else
            {
                var contract = serializer.ContractResolver.ResolveContract(value.GetType());
                if (contract is JsonPrimitiveContract)
                {
                    var wrapper = TypeWrapper.CreateWrapper(value);
                    serializer.Serialize(writer, wrapper, typeof(object));
                }
                else
                {
                    serializer.Serialize(writer, value);
                }
            }
        }
    }

    public abstract class TypeWrapper
    {
        protected TypeWrapper() { }

        [JsonIgnore]
        public abstract object ObjectValue { get; }

        public static TypeWrapper CreateWrapper<T>(T value)
        {
            if (value == null)
                return new TypeWrapper<T>();
            var type = value.GetType();
            if (type == typeof(T))
                return new TypeWrapper<T>(value);
            // Return actual type of subclass
            return (TypeWrapper)Activator.CreateInstance(typeof(TypeWrapper<>).MakeGenericType(type), value);
        }
    }

    public sealed class TypeWrapper<T> : TypeWrapper
    {
        public TypeWrapper() : base() { }

        public TypeWrapper(T value)
            : base()
        {
            this.Value = value;
        }

        public override object ObjectValue { get { return Value; } }

        public T Value { get; set; }
    }

    public enum Foo { A, B, C }
    public enum Bar { A, B, C }
    public class Misc { public Foo Foo { get; set; } }

    public static class ObjectExtensions
    {
        public static Type GetTypeSafe(this object obj)
        {
            if (obj == null)
                return null;
            return obj.GetType();
        }
    }

    public class TestClass
    {
        public static void Test()
        {
            var dict = new Dictionary<string, object>();
            dict.Add("a", Foo.A);
            dict.Add("b", Bar.B);
            dict.Add("c", new Misc());
            dict.Add("bool", true);
            dict.Add("DateTime", DateTime.Today);
            dict.Add("string", "a string value");
            dict.Add("int", int.MaxValue);
            dict.Add("uint", uint.MaxValue);
            dict.Add("long", long.MaxValue - 1);
            dict.Add("ulong", (ulong)long.MaxValue);
            dict.Add("short", short.MaxValue);
            dict.Add("ushort", ushort.MaxValue);
            dict.Add("char", 'c');
            dict.Add("Null", null);

            var settings = new JsonSerializerSettings
            {
                TypeNameHandling = TypeNameHandling.All,
                ContractResolver = UntypedToTypedValueContractResolver.Instance,
                Converters = new [] { new StringEnumConverter() }, // If you prefer

				TypeNameAssemblyFormat = System.Runtime.Serialization.Formatters.FormatterAssemblyStyle.Full, // Required on dotnetfiddle
            };

            var json = JsonConvert.SerializeObject(dict, Formatting.Indented, settings);

            Console.WriteLine(json);

            var dict2 = JsonConvert.DeserializeObject<Dictionary<string, object>>(json, settings);

            foreach (var pair in dict)
            {
                object value2;

                if (!dict2.TryGetValue(pair.Key, out value2))
                {
                    throw new InvalidOperationException();
                }
                else
                {
                    if (pair.Value.GetTypeSafe() != value2.GetTypeSafe())
                    {
                        throw new InvalidOperationException();
                    }

                    if (value2 is IConvertible &&
                        !EqualityComparer<object>.Default.Equals(pair.Value, value2))
                    {
                        throw new InvalidOperationException();
                    }
                }
            }
            Console.WriteLine("dict deserialized successfully, all values have the same type.");
        }
    }
					
	public class Program
	{
		public static void Main()
		{
			Console.WriteLine("Json.NET version: " + typeof(JsonSerializer).Assembly.FullName);
			Console.WriteLine("");
				
			TestClass.Test();
		}
	}
;