Json.NET简单接口序列化

本文关键字:序列化 接口 简单 NET Json | 更新日期: 2023-09-27 18:28:06

我正在尝试使用json.NET将IAnimal实例对象序列化为json。等级结构:

public class Dog : IAnimal {
    public int Width { get; set; }
    public double Bark { get; set; }
}
public class Cat : IAnimal {
    public int Width { get; set; }
    public double Meow { get; set; }
}
public interface IAnimal {
    int Width { get; set; }
}
public class AnimalContainer {
    public IAnimal Animal { get; set; }
}

尝试了这种方式(请注意,我在其他线程中使用了"TypeNameHandling.Auto"):

public void IAnimal_ShouldBeJsonSerializable() {
        var animal = new AnimalContainer {Animal = new Dog {Bark = 5, Width = 2}};
        var json = JsonConvert.SerializeObject(animal,
            new JsonSerializerSettings{TypeNameHandling = TypeNameHandling.Auto});
        var deserializedAnimal = JsonConvert.DeserializeObject<AnimalContainer>(json);
    }

但引发了一个异常,即"无法创建类型IAnimal的实例,类型是接口或抽象类,无法实例化"。但是json包含了具体的类型信息!

我怎样才能让它工作?

Json.NET简单接口序列化

看起来并没有将序列化程序设置传递给DeserializeObject调用。您需要在序列化和反序列化中都包含TypeNameHandling

var animal = new AnimalContainer { Animal = new Dog { Bark = 5, Width = 2 } };
var settings = new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.Auto };
var json = JsonConvert.SerializeObject(animal, settings);
var deserializedAnimal = JsonConvert.DeserializeObject<AnimalContainer>(json, settings);
Console.WriteLine(deserializedAnimal.Animal.GetType().Name);