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

问题描述

我消耗返回这样的字符串值的API。 部分-枚举值



我试图把这些值枚举,因为默认StringEnumConverter不做我尝试这个装饰器与一些额外的逻辑工作。我怎样才能确保值正确反序列化?



下面的代码是我试训得到这个工作做好。然而,行读者=新JsonTextReader(新StringReader(清洁)); 更是打破了整个事情,因为base.ReadJson不能识别字符串作为JSON



是否有这样做,而不必实施StringEnumConverter所有excisting逻辑更好的办法? ?如何解决我的做法

 公共类BkStringEnumConverter:StringEnumConverter 
{
公众覆盖对象ReadJson(JsonReader读者类型的objectType,对象existingValue,JsonSerializer串行)
{
如果(reader.TokenType == JsonToken.String)
{
VAR enumString = reader.Value.ToString() ;
如果(enumString.Contains( - ))
{
VAR清洗= enumString.Split( - )选择(FirstToUpper).Aggregate((A,B)=过夜。 ; A + b);
=读者新JsonTextReader(新StringReader(清洁));
}
}
返回base.ReadJson(读者的objectType,existingValue,序列化);
}

私人静态字符串FirstToUpper(字符串输入)
{
VAR firstLetter = input.ToCharArray()。第一个()。toString()方法。ToUpper的() ;
返回string.IsNullOrEmpty(输入)
?输入
:firstLetter +的string.join(,input.ToCharArray()跳过(1));
}
}


解决方案

我加入我的枚举值EnumMember属性解决了这个问题。该Json.NET默认 StringEnumConverter 完美处理与这些属性。



例如:

 公共枚举MyEnum 
{
[EnumMember(一些-枚举值)]
SomeEnumValue,
价值
[EnumMember(一些,其他的价值)]
SomeOtherValue
}

请注意,您只有在短线,或者你不能在你的枚举使用其他特殊字符的情况下,指定的属性。大写小写是由 StringEnumConverter 处理。因此,如果服务返回象 someenumvalue 的值应该在枚举 Someenumvalue 这样使用它。如果你喜欢 SomeEnumValue 你应该使用 EnumMember 属性。在情况下,服务会返回像这样 someEnumValue 你可以使用它像这样 SomeEnumValue (它的工作原理开箱当您使用CamelCaseText属性)。



您可以很容易地指定您的转换器和 JsonSerializerSettings


$其它设置b $ b

下面是我用我自己设定的例子。

 新JsonSerializerSettings 
{
ContractResolver =新CamelCasePropertyNamesContractResolver(),
=转换器新的List< JsonConverter> {新StringEnumConverter {CamelCaseText =真}}
NullValueHandling = NullValueHandling.Ignore
};


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

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?

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.

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));
    }
}
解决方案

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

Example:

public enum MyEnum
{
    [EnumMember("some-enum-value")]
    SomeEnumValue,
    Value,
    [EnumMember("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.

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

这篇关于HOWTO装饰JSON.NET StringEnumConverter的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-23 15:02