gpt4 book ai didi

c# - 如何序列化从字典派生的类

转载 作者:太空狗 更新时间:2023-10-30 01:02:41 26 4
gpt4 key购买 nike

我正在尝试使用 Json.Net 将以下类序列化/反序列化为 Json:

public class ChildDictionary:Dictionary<Employee, double>
{

public string Name { get; set; }

}

我找到了资料here , here , 和 here这些是相关的,但它们都没有专门处理在我们从字典派生的这种情况下语法应该是什么样子。

员工自行使用 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;
}
}

我不在乎Json最后长什么样,只要能读写不丢数据就行

有什么关于完成此任务的代码的建议吗?自定义 JsonConverter 或属性都是很好的解决方案。

最佳答案

因为你的字典有一个复杂的键和额外的属性,你将需要使用一个自定义的 JsonConverter 来序列化和反序列化这个类。下面是一个应该完成这项工作的转换器。它分两部分处理序列化:首先它使用反射来处理类上的任何读写属性,然后将对象转换为字典接口(interface)来处理键值对。后者作为具有 KeyValue 属性的对象数组写入 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());
}
}

要使用转换器,您可以用这样的 [JsonConverter] 属性标记您的类(确保通用参数与您的类继承自的字典的参数匹配):

[JsonConverter(typeof(ComplexDictionaryConverter<Employee, double>))]
public class ChildDictionary : Dictionary<Employee, double>
{
...
}

这是一个展示完整往返的演示:

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

fiddle :https://dotnetfiddle.net/fTfoIk

关于c# - 如何序列化从字典派生的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32847117/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com