Getting Newtonsoft Json.NET to respect the DataMember Name property

Json.NET is brilliant, not least because it produces much more sensible JSON in a number of situations than the DataContractJsonSerializer but also because there aren’t many problems that can’t be solved by adding appropriate attributes or formatters.

Sometimes you need to output specific names for enumeration members – in most cases the enumeration member name itself, and Json.NET comes with the StringEnumConverter for this purpose and it works well – just decorate the enumeration itself with the JsonConverter attribute and you’re done.

In some cases though you need to output values that wouldn’t otherwise be valid C# identifiers – for example, the string ‘A128CBC-HS256’ for an enumeration member ‘A128CBC_HS256’ (where we want that underscore turned into a dash). Adding DataMember attributes to the enumeration members doesn’t work, so I threw the following together quickly to respect them where present.

Presented as-is and without much testing – in particular there’ll be a performance hit for this as we’re using reflection to render and parse the values.

Example enumeration:

[DataContract]
[JsonConverter(typeof(DataMemberAwareEnumJsonConverter))]
public enum EncryptionMethod
{
  [DataMember(Name = "A128CBC-HS256")]
  A128CBC_HS256,
  [DataMember(Name = "A256CBC-HS512")]
  A256CBC_HS512
}

 

Leave a Reply

Your email address will not be published. Required fields are marked *