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

时间:2016-04-06 12:59:50

标签: json json.net

我正在使用此类作为枚举的基类: link 我创建了一个自定义的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);
    }
}

我做错了什么?

1 个答案:

答案 0 :(得分:2)

JsonReader.ReadAsInt32()从流中读取 next JSON令牌。您需要当前标记的值。所以:

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