如何装饰JSON.NET StringEnumConverter [英] How to decorate JSON.NET StringEnumConverter

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

问题描述

我正在使用一个api,它返回这样的字符串值. some-enum-value

I'm consuming an api which returns string values like this. some-enum-value

我尝试将这些值放在一个枚举中,因为默认的StringEnumConverter不能完成工作,因此我尝试用一​​些附加逻辑来装饰此Converter.如何确保正确反序列化了这些值?

I try to put these values in an enum, since the default StringEnumConverter doesn't do the job I try to decorate this Converter with some additional logic. How can I make sure the values are correctly deserialized?

下面的代码是我完成此工作的尝试.但是reader = new JsonTextReader(new StringReader(cleaned));行破坏了整个过程,因为base.ReadJson无法将字符串识别为JSON.

Following code is my tryout to get this job done. However the line reader = new JsonTextReader(new StringReader(cleaned)); is breaking the whole thing since the base.ReadJson cant recognize the string as JSON.

是否有更好的方法可以执行此操作而不必在StringEnumConverter中实现所有现有逻辑?如何解决我的方法?

Is there a better way of doing this without having to implement all the excisting logic in StringEnumConverter? How to 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天全站免登陆