CSharp · Console
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<ISubStuff, SubStuff>))]
public Dictionary<string, ISubStuff> SubStuff
{
get;
set;
}
}
public class TypeConverter<T, TSerialized> : CustomCreationConverter<T>
where TSerialized : T, new()
{
public override T Create(Type objectType)
{
return new TSerialized();
}
}
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; }
}