0

I have an enum which contains attributes on each value, for example:

public enum MyEnum 
{
    [MyEnumAttribute("val01")]
    Value01,
    
    [MyEnumAttribute("val02")]
    Value02
}

This enum is used as a property in a class, for example:

public class MyDataObject 
{
    public string Name { get; set; }
    public MyEnum EnumOption { get; set; }
}

How can I serialize this object to JSON (preferably using Newtonsoft.Json), using the value from MyEnumAttribute instead of the enum value?

Edit:

Ideally, I'd also like to be able to deserialise the JSON into an instance of MyDataObject, mapping the values val01 to MyEnum.Value01, val02 to MyEnum.Value02 etc

Community
  • 1
  • 1
devklick
  • 2,000
  • 3
  • 30
  • 47
  • or if you don't want custom converter - then easy & dirty way - add ignore to enum property + provide additional string property with get / set logic for (de)serialization based on custom attributes – Lanorkin Jul 02 '19 at 15:19
  • Does it have to be a *custom* attribute? Json.NET's `StringEnumConverter` does support `EnumMemberAttribute` as shown in [How to serialize enums to different property name using json.net](https://stackoverflow.com/q/26391632) and [parsing an enumeration in JSON.net](https://stackoverflow.com/q/7799769). – dbc Jul 02 '19 at 19:33
  • @dbc You're absolutely right, and that's all I need in the short term, thanks. At some point I'll need to include more properties in the attribute, in which case it sounds like I'll need a custom enum converter, which doesnt seem too bad. – devklick Jul 02 '19 at 19:45

0 Answers0