Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I pass properties to a StringEnumConverter in a JsonConverterAttribute

Tags:

c#

json.net

I'm trying to serialize a list of objects to JSON using Newtonsoft's JsonConvert. My Marker class includes an enum, and I'm trying to serialize it into a camelCase string. Based on other Stackoverflow questions, I'm trying to use the StringEnumConverter:

public enum MarkerType
{
    None = 0,
    Bookmark = 1,
    Highlight = 2
}

public class Marker
{
    [JsonConverter(typeof(StringEnumConverter)]
    public MarkerType MarkerType { get; set; }
}

This partially works, but my MarkerType string is PascalCase when I call:

var json = JsonConvert.SerializeObject(markers, Formatting.None);

Result:

{
    ...,
    "MarkerType":"Bookmark"
}

What I'm really looking for is:

{
    ...,
    "MarkerType":"bookmark"
}

The StringEnumConverter docs mention a CamelCaseText property, but I'm not sure how to pass that using the JsonConverterAttribute. The following code fails:

[JsonConverter(typeof(StringEnumConverter), new object[] { "camelCaseText" }]

How do I specify the CamelCaseText property for the StringEnumConverter in a JsonConverterAttribute?

like image 729
Brian Avatar asked Jun 13 '16 16:06

Brian


1 Answers

JsonConverterAttribute has two constructors, one of which takes a parameter list (Object[]). This maps to the constructor of the type from the first parameter.

StringEnumConverter can handle this with most of its non-default constructors.

The first one is obsolete in JSON.net 12+

The second one allows you to specify a NamingStrategy Type; the CamelCaseNamingStrategy does the trick. Actually, this is true for three out of the six constructors provided.

Note: one other constructor breaks the mold, asking for an instance of a NamingStrategy instead of a type.

It would look like this:

[JsonConverter(typeof(StringEnumConverter), typeof(CamelCaseNamingStrategy))]
public MarkerType MarkerType { get; set; }
like image 73
Brian Avatar answered Sep 19 '22 14:09

Brian