Selecting a NamingStrategy when using a JsonConverter on a class property
Asked Answered
S

3

9

I've got a c# class that I am trying to correctly serialise using Newtonsoft.Json. The property is an enumeration type and I wish the value to be serialised as the "lowercase version of the enumeration name". There is a JsonConverterAttribute available for specifying this on the property and also a prewritten StringEnumConverter but I need to specify the CamelCaseNamingStrategy on that converter but I can't work out the syntax.

I've tried to assign it on the property itself:

public class C
{
    [JsonConverter(typeof(StringEnumConverter),NamingStrategy=typeof(CamelCaseNamingStrategy))]
    public ChartType ChartType { get; set; }
}

and I've also tried adding it similarly onto the enumeration type itself:

[JsonConverter(typeof(StringEnumConverter),NamingStrategy=typeof(CamelCaseNamingStrategy))]
public enum ChartType { Pie, Bar }

But the syntax is wrong. I can't find any examples of this in the Newtonsoft documentation.

The desired serialision would be: "ChartType":"pie" or "ChartType":"bar"

Any ideas? Thanks.

Substantial answered 1/2, 2019 at 17:51 Comment(0)
S
13

Okay, this appears to work:

[JsonProperty("type")] 
[JsonConverter(typeof(StringEnumConverter), 
     converterParameters:typeof(CamelCaseNamingStrategy))]
public ChartType ChartType { get; }  

As NamingStrategy is a property of the StringEnumConverter it's applied using the converterParameters parameter. This got my desired output. I think an example of this would be useful in Newtonsoft documentation.

Substantial answered 1/2, 2019 at 17:58 Comment(0)
U
8

Another possible solution is using JsonSerializerSettings

var settings = new JsonSerializerSettings
{
    Converters = new List<JsonConverter> {
        new StringEnumConverter(new CamelCaseNamingStrategy())
    }
};
var result = JsonConvert.SerializeObject(obj, settings);
Unclothe answered 1/2, 2019 at 18:57 Comment(0)
D
2

This works for me for enabling camel casing on a single place in a .Net Core web api:

[JsonConverter(typeof(StringEnumConverter), true)]

Note that you can append constructor parameters to the type given by the first parameter and StringEnumConverter has the following overloaded constructor:

StringEnumConverter(bool camelCaseText)

Of course, enabling this globally is normally preferred, as discussed here for example.

Diplodocus answered 2/4, 2019 at 10:26 Comment(1)
For what it's worth, the boolean camelCaseText parameter used here has been marked obsolete. See newtonsoft.com/json/help/html/…Pro

© 2022 - 2024 — McMap. All rights reserved.