使用json.net将整数数组反序列化为对象数组



我使用这个类作为枚举的基类:链接我创建了一个自定义的json.net转换器来处理序列化/反序列化对象时的枚举。序列化工作正常,但是当我试图反序列化具有枚举集合属性的对象时,json.net抛出一个SerializationException,并显示以下消息:

反序列化数组时意外结束。路径",第11行,位置2。

更新:以下是我的所有类,它们带有Enumeration类的精简版本。

public class Program
{
    static void Main(string[] args)
    {
        var employee = new Employee
        {
            Name="asd",
            Types = new List<EmployeeType>()
            {
                EmployeeType.AssistantToTheRegionalManager,
                EmployeeType.Manager,
                EmployeeType.Servant
            }
        };
        var json = JsonConvert.SerializeObject(employee, new EnumerationTypeConverter());
        var deserializedEmployee=JsonConvert.DeserializeObject<Employee>(json,new EnumerationTypeConverter());
    }
}
public class Employee
{
    public string Name { get; set; }
    public List<EmployeeType> Types { get; set; }
}

public class EmployeeType : Enumeration
{
    public static readonly EmployeeType Manager
        = new EmployeeType(0, "Manager");
    public static readonly EmployeeType Servant
        = new EmployeeType(1, "Servant");
    public static readonly EmployeeType AssistantToTheRegionalManager
        = new EmployeeType(2, "Assistant to the Regional Manager");
    public EmployeeType() { }
    private EmployeeType(int value, string displayName) : base(value, displayName) { }
}
public class EnumerationTypeConverter : JsonConverter
{
    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        writer.WriteValue((value as Enumeration).Value);
    }
    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        int? value = reader.ReadAsInt32();
        return value.HasValue ? Enumeration.FromValue(value.Value, objectType) : null;
    }
    public override bool CanConvert(Type objectType)
    {
        return objectType.IsSubclassOf(typeof(Enumeration));
    }
}
public abstract class Enumeration
{
    public int Value
    {
        get; set;
    }
    public string DisplayName { get; set; }
    protected Enumeration(int value, string displayName)
    {
        Value = value;
        DisplayName = displayName;
    }        
    public static IEnumerable<Enumeration> GetAll(Type type)
    {
        var fields = type.GetFields(BindingFlags.Public | BindingFlags.Static | BindingFlags.DeclaredOnly);
        foreach (var fieldInfo in fields)
        {
            yield return fieldInfo.GetValue(null) as Enumeration;
        }
    }
    public static object FromValue(int value, Type type)
    {
        return GetAll(type).FirstOrDefault(p => p.Value == value);
    }
}

我做错了什么?

JsonReader.ReadAsInt32()从流中读取下一个JSON令牌。您需要当前令牌的值。那么做:

var value = (int?)JToken.Load(reader);

相关内容

  • 没有找到相关文章