如何使 JSON.NET StringEnumConverter 使用连字符分隔的大小写 [英] How to make JSON.NET StringEnumConverter use hyphen-separated casing

查看:16
本文介绍了如何使 JSON.NET StringEnumConverter 使用连字符分隔的大小写的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用了一个 API,它返回这样的字符串值:

I consume an API which returns the string values like this:

some-enum-value

我尝试将这些值放在 enum 中,因为默认的 StringEnumConverter 没有做我想要的,这是用一些额外的逻辑来装饰这个转换器.

I try to put these values in an enum , since the default StringEnumConverter doesn't do what I want, which is to to decorate this Converter with some additional logic.

我如何确保值被反序列化正确?

以下代码是我完成这项工作的尝试.
然而行

The following code is my tryout to get this job done.
However the line

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

破坏了整个事情,因为 base.ReadJson 无法将字符串识别为 JSON.

breaks the whole thing since the base.ReadJson can't recognize the string as a JSON.

是否有更好的方法来做到这一点,而无需在 StringEnumConverter 中实现所有现有逻辑?
我该如何修正我的方法?

Is there a better way to do this without having to implement all the existing logic in a StringEnumConverter?
How could I fix my approach?

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

推荐答案

我通过在枚举值上添加 EnumMember 属性解决了这个问题.Json.NET 默认的 StringEnumConverter 完美地处理了这些属性.

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
}

请注意,如果您不能在枚举中使用破折号或其他特殊字符,您只需指定属性.大写小写由 StringEnumConverter 处理.因此,如果服务返回一个类似于 someenumvalue 的值,您应该在枚举 Someenumvalue 中像这样使用它.如果您更喜欢 SomeEnumValue,则应使用 EnumMember 属性.如果服务像这样返回它 someEnumValue 你可以像这样使用它 SomeEnumValue(当你使用 CamelCaseText 属性时它开箱即用).

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).

您可以在 JsonSerializerSettings 中轻松指定转换器和其他设置.

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

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

Here is an example of the settings I use myself.

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

这篇关于如何使 JSON.NET StringEnumConverter 使用连字符分隔的大小写的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆