Question40620323 using-json-net-converter-to-deserialize-dictionary-with-interface-value

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;


	public interface ISubStuff
	{
		string Item { get; set; }
	}
	
	public class SubStuff : ISubStuff
	{
	   public string Item { get; set; }
	}
	
	public interface IMainStuff
	{
		Dictionary<string, ISubStuff> SubStuff { get; set; }
	}

	public class MainStuff : IMainStuff
	{ 
		[JsonProperty(ItemConverterType = typeof(TypeConverter<SubStuff>))]
		public Dictionary<string, ISubStuff> SubStuff
		{ 
			get; 
			set; 
		} 
	}

	public class TypeConverter<T> : JsonConverter
	{
		public override bool CanConvert(Type objectType) 
		{
			var msg = string.Format("This converter should be applied directly with [JsonProperty(ItemConverterType = typeof(TypeConverter<{0}>))] or [JsonProperty(typeof(TypeConverter<{0}>))]", 
									typeof(T));
            throw new NotImplementedException(msg);
		}
		
        public override bool CanWrite { get { return false; } }

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

		public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
		{
			return serializer.Deserialize<T>(reader);
		}
	}
	
	public class Program
	{
		static void Test()
		{
			var root = new MainStuff
			{
				SubStuff = new Dictionary<string, ISubStuff>()
				{
					{ "key1", new SubStuff { Item = "hello 1" } },
					{ "key2", new SubStuff { Item = "hello 2" } },
				},
			};
			
			var json1 = JsonConvert.SerializeObject(root);
			
			Console.WriteLine(json1);
			
			var root2 = JsonConvert.DeserializeObject<MainStuff>(json1);
			
			var json2 = JsonConvert.SerializeObject(root2);
			
			Console.WriteLine(json2);
		}
		
		public static void Main()
		{
			try
			{
				Test();
			}
			catch (Exception ex)
			{
				Console.WriteLine(ex);
				throw;
			}
		}
	}

	public class UnrelatedSubStuff : ISubStuff
	{
	   public string Item { get; set; }
	}	

;