13

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?

1 Answer 1

27

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; }
2
  • As of Newtonsoft.Json v 12, there are 5 non-default constructors, including two that have options for allowIntegerValues.
    – user3896255
    Commented Nov 6, 2019 at 16:59
  • 1
    @WebHead Thanks for the note! I've updated the answer to take the new constructors into account.
    – Brian
    Commented Nov 6, 2019 at 20:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.