In my class, I have an enum definition as followed:
public enum ChangeType {
[EnumMember(Value ="Added")]
Added,
[EnumMember(Value = "Removed")]
Removed,
[EnumMember(Value = "Updated")]
Updated
}
And in the class definition, I have a property:
public
Dictionary<string, (ChangeType changType, string oldValue, string newValue)>
PropertyChanges { get; set; }
Requirements:
What I have tried:
Question:
Can I achieve the above without writing a custom converter to convert the whole 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.
So you'll have to use a class to control the serialized names, instead of that 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.
First, I create a class called CustomTupleConverter that implements JsonConverter<(ChangeType changeType, string oldValue, string newValue)> .
In the implementation of WriteJson(), I have the following:
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(cc, Formatting.Indented, new CustomTupleConverter());
That's it.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.