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?