C# 如何序列化从字典派生的类
我正在尝试使用Json.Net在Json中序列化/反序列化以下类:C# 如何序列化从字典派生的类,c#,json,dictionary,serialization,json.net,C#,Json,Dictionary,Serialization,Json.net,我正在尝试使用Json.Net在Json中序列化/反序列化以下类: public class ChildDictionary:Dictionary<Employee, double> { public string Name { get; set; } } 公共类ChildDictionary:字典 { 公共字符串名称{get;set;} } 我已经找到了相关的信息,但是没有一个是专门针对我们从字典派生的情况下的语法应该是什么样子的 员工自己成功地使用Json.Net
public class ChildDictionary:Dictionary<Employee, double>
{
public string Name { get; set; }
}
公共类ChildDictionary:字典
{
公共字符串名称{get;set;}
}
我已经找到了相关的信息,但是没有一个是专门针对我们从字典派生的情况下的语法应该是什么样子的
员工自己成功地使用Json.Net序列化。看起来是这样的:
[JsonObject(MemberSerialization.OptIn)]
public class Employee
{
[JsonProperty]
public string Name { get; set; }
[JsonProperty]
public double Factor { get; set; }
[JsonProperty]
public List<ILoadBuilder> LoadBuilders = new List<ILoadBuilder>();
[JsonConstructor]
public LoadCause(string name, double factor, List<ILoadBuilder> loadBuilders)
{
this.Name = name;
this.DurationFactor = Factor;
this.LoadBuilders = loadBuilders;
}
}
[JsonObject(MemberSerialization.OptIn)]
公营雇员
{
[JsonProperty]
公共字符串名称{get;set;}
[JsonProperty]
公共双因子{get;set;}
[JsonProperty]
public List LoadBuilders=new List();
[JsonConstructor]
公共LoadCause(字符串名称、双因素、列表loadBuilders)
{
this.Name=Name;
此。持续系数=系数;
this.LoadBuilders=LoadBuilders;
}
}
我不在乎Json最终会是什么样子,只要我可以在不丢失数据的情况下编写和读取它
关于实现这一点的代码应该是什么样子的,有什么建议吗?自定义JsonConverter或属性都是很好的解决方案。因为您的字典既有复杂的键又有附加属性,所以您需要使用自定义的
JsonConverter
来序列化和反序列化此类。下面是一个转换器,应该做的工作。它分两部分处理序列化:首先使用反射处理类上的任何读写属性,然后将对象强制转换到字典接口以处理键值对。后者作为具有Key
和Value
属性的对象数组写入JSON,这样就可以管理复杂的键,而无需跳转到额外的环
public class ComplexDictionaryConverter<K,V> : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return (objectType.GetInterfaces().Any(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IDictionary<K,V>)));
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
JObject obj = new JObject();
foreach (PropertyInfo prop in GetReadWriteProperties(value.GetType()))
{
object val = prop.GetValue(value);
obj.Add(prop.Name, val != null ? JToken.FromObject(val, serializer) : new JValue(val));
}
JArray array = new JArray();
foreach (var kvp in (IDictionary<K, V>)value)
{
JObject item = new JObject();
item.Add("Key", JToken.FromObject(kvp.Key, serializer));
item.Add("Value", kvp.Value != null ? JToken.FromObject(kvp.Value, serializer) : new JValue(kvp.Value));
array.Add(item);
}
obj.Add("KVPs", array);
obj.WriteTo(writer);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
JObject obj = JObject.Load(reader);
IDictionary<K, V> dict = (IDictionary<K, V>)Activator.CreateInstance(objectType);
foreach (PropertyInfo prop in GetReadWriteProperties(objectType))
{
JToken token = obj[prop.Name];
object val = token != null ? token.ToObject(prop.PropertyType, serializer) : null;
prop.SetValue(dict, val);
}
JArray array = (JArray)obj["KVPs"];
foreach (JObject kvp in array.Children<JObject>())
{
K key = kvp["Key"].ToObject<K>(serializer);
V val = kvp["Value"].ToObject<V>(serializer);
dict.Add(key, val);
}
return dict;
}
private IEnumerable<PropertyInfo> GetReadWriteProperties(Type type)
{
return type.GetProperties().Where(p => p.CanRead && p.CanWrite && !p.GetIndexParameters().Any());
}
}
下面是一个演示,展示了完整的往返过程:
class Program
{
static void Main(string[] args)
{
ChildDictionary dict = new ChildDictionary();
dict.Name = "Roster";
dict.Add(new Employee { Id = 22, Name = "Joe", HireDate = new DateTime(2012, 4, 17) }, 1923.07);
dict.Add(new Employee { Id = 45, Name = "Fred", HireDate = new DateTime(2010, 8, 22) }, 1415.25);
string json = JsonConvert.SerializeObject(dict, Formatting.Indented);
Console.WriteLine(json);
dict = JsonConvert.DeserializeObject<ChildDictionary>(json);
Console.WriteLine("Name: " + dict.Name);
foreach (var kvp in dict)
{
Console.WriteLine("Employee Id: " + kvp.Key.Id);
Console.WriteLine("Employee Name: " + kvp.Key.Name);
Console.WriteLine("Employee Hire Date: " + kvp.Key.HireDate);
Console.WriteLine("Amount: " + kvp.Value);
Console.WriteLine();
}
}
}
[JsonConverter(typeof(ComplexDictionaryConverter<Employee, double>))]
public class ChildDictionary : Dictionary<Employee, double>
{
public string Name { get; set; }
}
public class Employee
{
public int Id { get; set; }
public string Name { get; set; }
public DateTime HireDate { get; set; }
}
Fiddle:您希望输出是什么样的?我不在乎,只要我能在Maybe中写下来并读回它。这一条:非常感谢您为这个答案付出的所有努力!这几乎对我有用。反序列化只发生了一件奇怪的事情。每个Employee对象的一个属性(即列表)中都有重复的条目。有什么想法吗?如果需要,我可以添加employee类的更多细节,这可能是因为您正在初始化构造函数中的列表。Json.Net将在反序列化期间使用现有列表并添加到其中,而不是替换整个列表。有一个设置可用于更改此行为。这可能对你有用。看到了吗,就这样。非常感谢!没问题;很乐意帮忙。
class Program
{
static void Main(string[] args)
{
ChildDictionary dict = new ChildDictionary();
dict.Name = "Roster";
dict.Add(new Employee { Id = 22, Name = "Joe", HireDate = new DateTime(2012, 4, 17) }, 1923.07);
dict.Add(new Employee { Id = 45, Name = "Fred", HireDate = new DateTime(2010, 8, 22) }, 1415.25);
string json = JsonConvert.SerializeObject(dict, Formatting.Indented);
Console.WriteLine(json);
dict = JsonConvert.DeserializeObject<ChildDictionary>(json);
Console.WriteLine("Name: " + dict.Name);
foreach (var kvp in dict)
{
Console.WriteLine("Employee Id: " + kvp.Key.Id);
Console.WriteLine("Employee Name: " + kvp.Key.Name);
Console.WriteLine("Employee Hire Date: " + kvp.Key.HireDate);
Console.WriteLine("Amount: " + kvp.Value);
Console.WriteLine();
}
}
}
[JsonConverter(typeof(ComplexDictionaryConverter<Employee, double>))]
public class ChildDictionary : Dictionary<Employee, double>
{
public string Name { get; set; }
}
public class Employee
{
public int Id { get; set; }
public string Name { get; set; }
public DateTime HireDate { get; set; }
}
{
"Name": "Roster",
"KVPs": [
{
"Key": {
"Id": 22,
"Name": "Joe",
"HireDate": "2012-04-17T00:00:00"
},
"Value": 1923.07
},
{
"Key": {
"Id": 45,
"Name": "Fred",
"HireDate": "2010-08-22T00:00:00"
},
"Value": 1415.25
}
]
}
Name: Roster
Employee Id: 22
Employee Name: Joe
Employee Hire Date: 4/17/2012 12:00:00 AM
Amount: 1923.07
Employee Id: 45
Employee Name: Fred
Employee Hire Date: 8/22/2010 12:00:00 AM
Amount: 1415.25