我使用的API返回的字符串值如下:

some-enum-value

我try 将这些值放入enum,因为默认的StringEnumConverter不会执行我想要的操作,即使用一些额外的逻辑来修饰此Converter.

How can I be sure that the values are deserialized correctly ?

以下代码是我完成这项工作的试用版.

reader = new JsonTextReader(new StringReader(cleaned));

中断整个过程,因为base.ReadJson不能将字符串识别为JSON.

有没有更好的方法来做到这一点,而不需要在StringEnumConverter中实现所有现有的逻辑?
我怎么才能修复我的方法呢?

public class BkStringEnumConverter : StringEnumConverter
{
    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        if (reader.TokenType == JsonToken.String)
        {
            var enumString = reader.Value.ToString();
            if (enumString.Contains("-"))
            {
                var cleaned = enumString.Split('-').Select(FirstToUpper).Aggregate((a, b) => a + b);
                reader = new JsonTextReader(new StringReader(cleaned));
            }
        }
        return base.ReadJson(reader, objectType, existingValue, serializer);
    }

    private static string FirstToUpper(string input)
    {
        var firstLetter = input.ToCharArray().First().ToString().ToUpper();
        return string.IsNullOrEmpty(input)
            ? input
            : firstLetter + string.Join("", input.ToCharArray().Skip(1));
    }
}

推荐答案

I solved the issue by adding EnumMember attributes on my enum values. The Json.NET default StringEnumConverter perfectly deals with these attributes.

例子:

public enum MyEnum
{
    [EnumMember(Value = "some-enum-value")]
    SomeEnumValue,
    Value,
    [EnumMember(Value = "some-other-value")]
    SomeOtherValue
}

Please note that you only have to specify the attributes in case of dashes or other special chars you can't use in your enum. The uppercase lowercase is dealt with by the StringEnumConverter. So if the service returns a value like someenumvalue you should use it like this in the enum Someenumvalue. If you prefer SomeEnumValue you should use the EnumMember attribute. In case the service returns it like this someEnumValue you can just use it like this SomeEnumValue (It works out of the box when you use the CamelCaseText property).

You can easily specify your converters and other settings in the JsonSerializerSettings.

以下是我自己使用的设置示例.

new JsonSerializerSettings
{
    ContractResolver = new CamelCasePropertyNamesContractResolver(),
    Converters = new List<JsonConverter> { new StringEnumConverter { CamelCaseText = true } },
    NullValueHandling = NullValueHandling.Ignore
};

Json相关问答推荐

无法根据vega规范中的条件设置文本 colored颜色

使用相同的密钥值来命名Json并使用Jolt重命名密钥

Vega图表计数聚合如果数据值为空数组则不显示任何内容,如何解决此问题?

如何使用JQ打印每个根级对象键一行?

如何用JQ更改空/布尔/数字的 colored颜色 ?

如何在Haskell中解析JSON,其中字段的名称可以是多个值之一,但应该转换为单个Haskell类型?

在Reaction中从JSON文件中筛选数组

无法从MongoDB集合中检索正确的文档

XSLT 3.0 Json-to-xml,json 包含 html struct

使用 jq 获取所有嵌套键和值

从 json 对象中过滤掉所有出现的给定属性

Flask 请求和 application/json 内容类型

Java JSON 序列化 - 最佳实践

JSON 语法错误:'unexpected number' 或 'JSON.parse: expected ',' or '}' after property value in object'

在 Rails 3 中处理 JS/ERB 模板中的 JSON

使用 Retrofit 解析动态密钥 Json 字符串

Sequelize - 如何仅返回数据库结果的 JSON 对象?

如何让 javascript 从 .json 文件中读取?

python追加到json对象中的数组

在播放框架 JsObject 中解析 Json 数组