- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我正在尝试使用 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)来处理键值对。后者作为具有 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());
}
}
要使用转换器,您可以用这样的 [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/
我有一个无法理解的奇怪编译问题。 //I know, you should never derive from the STL Library template class SharedClass :
我是一个刚开始学习 Haskell 的菜鸟,所以如果我问愚蠢的问题,请耐心等待。 最近我在 SO 中遇到了演示如何导出函数和表达式的类型和实现的问题(诸如 How can I understand "
如何自动派生此 GADT 的 Read 实例: {-# LANGUAGE GADTs, StandaloneDeriving #-} data TypeDec a where TypeDecInt
我遇到了我想要的情况 Deal class要注意它DealDetail type反之亦然,我想 DealDetail注意Deal type .将来我想有很多 Deal 的后代和 DealDetails
我是 C# 新手,所以请多多包涵。 好的,所以我在不同的程序集中有两个类需要相互引用: namespace AssemblyA { class A { private B MyB {
简而言之,我已经实现了一个派生自 SynchronizationContext 的类,以便 GUI 应用程序可以轻松地使用在 GUI 线程以外的线程上引发的事件。我非常感谢对我的实现的评论。具体来说,
我正在设计一个小型系统,想知道如何为派生类分配内存的细微差别。 如果我有两个类(class) class foo { public: int a; Foo(): a(0) {}; }; class
我正在尝试编写一个派生 PartialEq 的枚举,其中包含一个手动执行此操作的特征对象。我使用了解决方案 here为了强制 Trait 的实现者编写相等方法。这无法编译: trait Trait {
以下代码可以编译(特别是 MyError 被识别为具有调试特性): use std::str; use std::fmt; #[derive(Debug)] enum MyError where F:
是否有一种简单的方法来注释结构中的字段,以便在派生 PartialEq 特征时忽略它们?例如: #[derive(PartialEq,Eq)] pub struct UndirectedGraph {
我正在编写代码来处理“Foo”类型的对象。 foo 是一种容器,为了提供对其元素的高效和抽象访问,它提供了 Element 类型的嵌套类。 Element 包装对象在容器中的位置。 现在,“Foo”可
假设如下: class child : public parent { public: fun1(parent * obj); //somewhere on the child class
我有几个模板类 template class Transition { public: virtual Cost getCost() = 0; }; template class St
我正在尝试使用自定义 QSortFilterProxyModel . 这是我的标题: #include class QSortFilterProxyModel_NumbersLast : publi
我正在使用 C# 和 mvc3。我在解决方案中添加了一个项目。我想创建一个新 Controller 并让它从我添加的项目中的 Controller 派生。我该怎么做? 最佳答案 在 Visual St
我在 python 中有一个对象,它派生自 QtGui.QGraphicsPixmapItem,具有一些基本属性和方法。在对此对象的引用上调用 deepcopy 后,当我尝试使用该副本时收到一条错误消
由于只能给FixedDocument添加页面,所以我写了一个派生类: public class CustomFixedDocument : FixedDocument { public voi
我在自定义 QMainWindow 时遇到了很大的问题,因为我不知道如何实现以下内容: 在 QMainWindow 文档中,QMainWindow 有一些用于工具栏、停靠小部件、状态栏和其他的特殊区域
我想感受一下QT,决定写一个小的十六进制编辑器。为此,我需要一个允许滚动的小部件。经过一番研究,我发现 QTextEdit 为此目的派生自 QAbstractScrollArea。在阅读 QAbstr
我正在寻找一种可以从已经发生的洗牌过程中派生出 key 的算法。 假设我们有被打乱的字符串“Hello”: "hello" -> "loelh" 现在我想从中导出一个 key k,我可以用它来撤销洗牌
我是一名优秀的程序员,十分优秀!