[Fork] [Fork] [Fork] https://stackoverflow.com/questions/64474856/c-sharp-using-newtonsoft-json-defaultcontractresolver-ivalueprovider-to-replace

CSharp · Console

/Program.cs

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization.Formatters;
using System.IO;
using System.Data;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Reflection;
using System.Collections.ObjectModel;

using System.Runtime.Serialization;

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

using NUnit.Framework; // Throws NUnit.Framework.AssertionException

using Debug = System.Console;

//https://stackoverflow.com/questions/64474856/c-sharp-using-newtonsoft-json-defaultcontractresolver-ivalueprovider-to-replace

	public class JsonTester
	{
		public void Test()
		{
			var d = new Outer();

			var json = JsonConvert.SerializeObject(d,
												   Formatting.Indented,
												   new JsonSerializerSettings()
												   {
													   ContractResolver = new JsonContractResolver()
												   });
			
			Console.WriteLine(json);
		}
	}

	public interface IVariant
	{
		object Data { get; }

		string TypeName { get; set; }
	}

	public interface IVariantData
	{
	}

	[DataContract]
	public class Variant<TEnum, TData> : IVariant where TEnum : struct where TData : class, IVariantData, new()
	{
		[DataMember]
		public TData Data { get; }

		public string TypeName { get; set; }

		object IVariant.Data => Data;

		public Variant()
		{
			Data = new TData();
		}
	}

	[DataContract]
	public sealed class VariantHolder
	{
		[DataContract]
		public class Joystick
		{
			[DataMember]
			public string Test { get; set; } = "Test";
		}

		[DataContract]
		public class Button
		{
			[DataMember]
			public string Test2 { get; set; } = "Test2";
		}

		[DataContract]
		public sealed class AimΞVariant : Variant<AimΞVariant.VariantEnum, AimΞVariant.VariantData>
		{
			public AimΞVariant()
			{
				TypeName = "Button";
			}
			public enum VariantEnum : byte
			{
				Joystick,
				Button
			}

			[DataContract]
			public sealed class VariantData : IVariantData
			{
				[DataMember]
				Joystick _Joystick = new Joystick();

				[DataMember]
				Button _Button = new Button();

				public Button Button => _Button;
				public Joystick Joystick => _Joystick;
			}
		}

		[DataMember]
		AimΞVariant Aim = new AimΞVariant();
	}

	[DataContract]
	public sealed class Outer
	{
		[DataMember]
		VariantHolder Data = new VariantHolder();
	}

    public class JsonContractResolver : DefaultContractResolver
    {
        protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
        {
			var property = base.CreateProperty(member, memberSerialization);
            if (typeof(IVariant).IsAssignableFrom(property.PropertyType))
            {
				property.ValueProvider = new IVariantValueProvider(member, property.PropertyType);
				property.DefaultValueHandling = DefaultValueHandling.Include;
				// The following fixes the InvalidCastException.  PropertyType has to be assignable from the type actually returned.
				// Since we don't know that at compile time, we need to set it to typeof(object).
				property.PropertyType = typeof(object);
				
				Debug.WriteLine("Used IVariantValueProvider for {0}", property);
			}
			return property;
        }

        protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
        {
            var list = type.GetProperties().Where(x => x.GetCustomAttributes().Any(a => a.GetType() == typeof(DataMemberAttribute))).Select(p =>
            {
				return CreateProperty(p, memberSerialization);
            }).Concat(
            type.GetFields(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public).Where(x => x.GetCustomAttributes().Any(a => a.GetType() == typeof(DataMemberAttribute))).Select(p =>
            {
				return CreateProperty(p, memberSerialization);
            })).ToList();

            return list;
        }
    }

    internal class IVariantValueProvider : IValueProvider
    {
        private MemberInfo member;
        private Type type;

        public IVariantValueProvider(MemberInfo member, Type type)
        {
            this.member = member;
            this.type = type;
        }

        public object GetValue(object target)
        {
			Debug.WriteLine("GetValue() called for {0}.{1}", target, member.Name);
		
            IVariant variant;

            switch (member)
            {
            case PropertyInfo p:
                variant = (IVariant)p.GetValue(target);
                break;
            case FieldInfo f:
                variant = (IVariant)f.GetValue(target);
                break;
            default:
                throw new InvalidCastException();
            }

            var dataType = variant.TypeName;

            var property = variant.Data.GetType().GetProperty(dataType);

            var value = property.GetValue(variant.Data);

			Debug.WriteLine("    Returned {0}", value);
            return value;
        }

        public void SetValue(object target, object value)
        {
            throw new NotImplementedException();
        }
    }

    class TestClass
    {
        public static void Test()
        {
			new JsonTester().Test();
		}	
	}

	public class Program
	{
		public static void Main()
		{
			Console.WriteLine("Environment version: {0} ({1})", System.Runtime.InteropServices.RuntimeInformation.FrameworkDescription , GetNetCoreVersion());
			Console.WriteLine("{0} version: {1}", typeof(JsonSerializer).Assembly.GetName().Name,  typeof(JsonSerializer).Assembly.FullName);
			Console.WriteLine();

			try
			{
				TestClass.Test();
			}
			catch (Exception ex)
			{
				Console.WriteLine("Failed with unhandled exception: ");
				Console.WriteLine(ex);
				throw;
			}
		}
		
		public static string GetNetCoreVersion()
		{
			//https://techblog.dorogin.com/how-to-detect-net-core-version-in-runtime-ecd65ad695be
			//
			var assembly = typeof(System.Runtime.GCSettings).GetTypeInfo().Assembly;
			var assemblyPath = assembly.CodeBase.Split(new[] { '/', '\\' }, StringSplitOptions.RemoveEmptyEntries);
			int netCoreAppIndex = Array.IndexOf(assemblyPath, "Microsoft.NETCore.App");
			if (netCoreAppIndex > 0 && netCoreAppIndex < assemblyPath.Length - 2)
				return assemblyPath[netCoreAppIndex + 1];
			return null;
		}
	}
;