简体   繁体   English

将带有元组和枚举的字典转换为 JSON

[英]Converting Dictionary with tuple and enum to JSON

In my class, I have an enum definition as followed:在我的 class 中,我的枚举定义如下:

public enum ChangeType { 
  [EnumMember(Value ="Added")]
  Added,
  [EnumMember(Value = "Removed")]
  Removed,
  [EnumMember(Value = "Updated")]
  Updated 
}

And in the class definition, I have a property:在 class 定义中,我有一个属性:

public 
  Dictionary<string, (ChangeType changType, string oldValue, string newValue)> 
  PropertyChanges { get; set; }

Requirements:要求:

  1. When converting to JSON, changeType should be in text, not number转换为 JSON 时,changeType 应该是文本,而不是数字
  2. Tuple should be converted w/ the name of the items instead of Item1, Item2 and Item3元组应使用项目名称而不是 Item1、Item2 和 Item3 进行转换

What I have tried:我试过的:

  • As for the enum, I tried putting the JsonConverter(typeof(StringEnumConverter))] in front of the property (no go)至于枚举,我尝试将 JsonConverter(typeof(StringEnumConverter))] 放在属性前面(不行)
  • Cannot any recommendation about the named tuples不能对命名元组提出任何建议

Question:问题:

Can I achieve the above without writing a custom converter to convert the whole class?我可以在不编写自定义转换器来转换整个 class 的情况下实现上述目标吗?

Thanks!谢谢!

The names of ValueTuple keys basically don't exist after compilation, except for in some attributes , so the type info that the serializer gets doesn't contain the names. ValueTuple 的键名在编译后基本不存在, 除了在某些属性中,所以序列化器获取的类型信息不包含名称。

So you'll have to use a class to control the serialized names, instead of that ValueTuple.因此,您必须使用 class 来控制序列化名称,而不是使用 ValueTuple。

It's actually not as bad as I thought... JsonConvert.SerializeObject() already has already done a pretty good job serializing the Dictionary<>, so all I have to do is to help Json to interpret the enum and the tuple.它实际上并没有我想象的那么糟糕...... JsonConvert.SerializeObject() 已经在序列化 Dictionary<> 方面做得很好,所以我所要做的就是帮助 Json 解释枚举和元组。

First, I create a class called CustomTupleConverter that implements JsonConverter<(ChangeType changeType, string oldValue, string newValue)> .首先,我创建了一个名为CustomTupleConverter的 class ,它实现了 JsonConverter<(ChangeType changeType, string oldValue, string newValue)>

In the implementation of WriteJson(), I have the following:在 WriteJson() 的实现中,我有以下内容:

writer.WriteStartObject();
writer.WritePropertyName("Action");
writer.WriteValue(value.changeType.ToString());
writer.WritePropertyName("OldValue");
writer.WriteValue(value.oldValue.ToString());
writer.WritePropertyName("NewValue");
writer.WriteValue(value.newValue.ToString());
writer.WriteEndObject();

When invoking the JsonConvert.SerializeObject() , I simply add the instantiation of my converter to the call:调用JsonConvert.SerializeObject()时,我只需将转换器的实例化添加到调用中:

JsonConvert.SerializeObject(cc, Formatting.Indented, new CustomTupleConverter());

That's it.而已。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM