I have an enumeration defined with C#, where I'm storing it's values as characters, like this:

public enum CardType
{
    Artist = 'A',
    Contemporary = 'C',
    Historical = 'H',
    Musician = 'M',
    Sports = 'S',
    Writer = 'W'
}

我正在try 使用JSON.NET进行反序列化,但是传入的JSON是使用CHAR值(字符串)而不是枚举的INT值编写的,如下所示:

[{"CardType","A"},{"CardType", "C"}]

Is it possible to define some kind of converter that will allow me to manually parse the char to the enum value?

我try 创建一个JsonConverter,但不确定如何创建,同时只将其应用于这个属性,而不是整个解析的对象.以下是我try 过的:

public class EnumerationConverter : JsonConverter
{
    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        serializer.Serialize(writer, value);
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        if (reader.TokenType == JsonToken.Null)
        {
            return null;
        }

        int value = serializer.Deserialize<int>(reader);
        return (CardType)value;
    }

    public override bool CanConvert(Type objectType)
    {
        return objectType.IsSubclassOf(typeof(string));
    }
}

逻辑可能是错误的,我可以解决这个问题,但问题是根本没有调用ReadJson().

CanConvert is, but it appears to be called for every property, not just the one property I defined it for:

public class Card
{
            private CardType type;
        [JsonConverter(typeof(EnumerationConverter))]
        public CardType Type
        {
            get { return type; }
            set { type = value; }
        }
}

我肯定我做得不对,但我很难找到关于如何为单个字段执行此操作的文档...

What am I missing?

推荐答案

您不需要定制JsonConverter,您可以使用内置StringEnumConverterEnumMemberAttribute的组合(来自System.Runtime.Serialization组件).

Without the EnumMemberAttribute it uses the enum names so Artist, Contemporary, etc so you need to change the names with it to your A,C, etc value.

But it is not the nicest solution because you have to repeat your values two times, but it works:

[JsonConverter(typeof(StringEnumConverter))]
public enum CardType
{
    [EnumMember(Value = "A")]
    Artist = 'A',
    [EnumMember(Value = "C")]
    Contemporary = 'C',
    [EnumMember(Value = "H")]
    Historical = 'H',
    [EnumMember(Value = "M")]
    Musician = 'M',
    [EnumMember(Value = "S")]
    Sports = 'S',
    [EnumMember(Value = "W")]
    Writer = 'W'
}

Json相关问答推荐

PowerShell脚本-替换json数组(转义$var将被视为不带双引号的文本)

合并二维数组的Jolt表达式

使用Jolt将字符串数组转换为JSON对象数组

如何使用JQ有条件 Select 值

我可以使用JQ来缩小数组中的json对象的范围吗?

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

使用JQ在数组中 Select 第一个具有匹配项的项

如何使用SQLite Trigger将JSON对象数组转换为新记录?

如何修复通过在 tsconfig.json 文件中添加allowImportingTsExtensions引发的错误 TS5023?

JOLT 在 struct 体中间添加一个 JSON 字段

Powershell - 如何从 JSON 中删除/过滤元素但保留其余部分?

使用 jq 获取特定键的所有父键

将文本转换为 python 列表

如何使用 gson 调用默认反序列化

如何为名称/值 struct 创建 JSON 模式?

Select 什么数据类型json或者jsonb或者text

如何安装 json gem - 无法构建 gem 原生扩展(mac 10.10)

ASP.NET Core API 仅返回列表的第一个结果

确保数组中的项目属性在 Json Schema 中是唯一的?

Volley JsonObjectRequest Post 参数不再起作用