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
?
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; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With