问题描述
我正在尝试使用Newtonsoft的JsonConvert将对象列表序列化为JSON.我的Marker类包含一个枚举,我正尝试将其序列化为camelCase字符串.基于其他Stackoverflow问题,我正在尝试使用StringEnumConverter
:
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; }
}
这部分起作用,但是当我打电话时我的MarkerType字符串是PascalCase
This partially works, but my MarkerType string is PascalCase when I call:
var json = JsonConvert.SerializeObject(markers, Formatting.None);
结果:
{
...,
"MarkerType":"Bookmark"
}
我真正想要的是:
{
...,
"MarkerType":"bookmark"
}
StringEnumConverter文档提到了CamelCaseText
属性,但我我不确定如何使用JsonConverterAttribute
传递它.以下代码失败:
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" }]
如何在JsonConverterAttribute
中为StringEnumConverter
指定CamelCaseText
属性?
推荐答案
JsonConverterAttribute 有两个构造函数,其中一个带有参数列表(Object[]
).这会从第一个参数映射到该类型的构造函数.
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 可以使用大多数非默认值来处理此问题构造函数.
StringEnumConverter can handle this with most of its non-default constructors.
第一个在JSON.net中已作废12+
The first one is obsolete in JSON.net 12+
第二个允许您指定 NamingStrategy 类型; CamelCaseNamingStrategy 可以解决问题.实际上,对于所提供的六个构造函数中的三个,这是正确的.
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.
注意:另一个构造函数打破了常规,要求NamingStrategy的实例而不是类型.
Note: one other constructor breaks the mold, asking for an instance of a NamingStrategy instead of a type.
它看起来像这样:
[JsonConverter(typeof(StringEnumConverter), typeof(CamelCaseNamingStrategy))]
public MarkerType MarkerType { get; set; }
这篇关于如何在JsonConverterAttribute中将属性传递给StringEnumConverter的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!