简体   繁体   中英

Converting Dictionary with tuple and enum to JSON

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:

  1. When converting to JSON, changeType should be in text, not number
  2. Tuple should be converted w/ the name of the items instead of Item1, Item2 and Item3

What I have tried:

  • As for the enum, I tried putting the JsonConverter(typeof(StringEnumConverter))] in front of the property (no go)
  • Cannot any recommendation about the named tuples

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.

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