How can I pass properties to a StringEnumConverter in a JsonConverterAttribute

戏子无情 提交于 2020-01-02 02:21:23

问题


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:


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; }


来源:https://stackoverflow.com/questions/37795279/how-can-i-pass-properties-to-a-stringenumconverter-in-a-jsonconverterattribute

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!