.NET 将 JSON 反序列化为多种类型

标签 .net json deserialization

这个问题在这里已经有了答案:




8年前关闭。




Possible Duplicate:
Deserializing JSON into one of several C# subclasses



我具有以下 JSON 架构的只读访问权限:
{ items: [{ type: "cat", catName: "tom" }, { type: "dog", dogName: "fluffy" }] }

我想将这些反序列化为各自的类型:
class Cat : Animal {
    string Name { get; set; }
}
class Dog : Animal {
    string Name { get; set; }
}

此时我唯一的想法是将它们反序列化为 dynamic对象,或 Dictionary<string, object>然后从那里构造这些对象。

我可能在其中一个 JSON 框架中遗漏了一些东西......

你的方法是什么? =]

最佳答案

我认为您可能需要反序列化 Json,然后从那里构造对象。直接反序列化为 CatDog不可能,因为反序列化器不知道如何专门构造这些对象。

编辑 : 从 Deserializing heterogenous JSON array into covariant List<> using JSON.NET 大量借款

像这样的事情会起作用:

interface IAnimal
{
    string Type { get; set; }
}

class Cat : IAnimal
{
    public string CatName { get; set; }
    public string Type { get; set; }
}

class Dog : IAnimal
{
    public string DogName { get; set; }
    public string Type { get; set; }
}

class AnimalJson
{
    public IEnumerable<IAnimal> Items { get; set; }
}

class Animal
{
    public string Type { get; set; }
    public string Name { get; set; }
}

class AnimalItemConverter : Newtonsoft.Json.Converters.CustomCreationConverter<IAnimal>
{
    public override IAnimal Create(Type objectType)
    {
        throw new NotImplementedException();
    }

    public IAnimal Create(Type objectType, JObject jObject)
    {
        var type = (string)jObject.Property("type");

        switch (type)
        {
            case "cat":
                return new Cat();
            case "dog":
                return new Dog();
        }

        throw new ApplicationException(String.Format("The animal type {0} is not supported!", type));
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        // Load JObject from stream 
        JObject jObject = JObject.Load(reader);

        // Create target object based on JObject 
        var target = Create(objectType, jObject);

        // Populate the object properties 
        serializer.Populate(jObject.CreateReader(), target);

        return target;
    }
}

string json = "{ items: [{ type: \"cat\", catName: \"tom\" }, { type: \"dog\", dogName: \"fluffy\" }] }";
object obj = JsonConvert.DeserializeObject<AnimalJson>(json, new AnimalItemConverter());

关于.NET 将 JSON 反序列化为多种类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12832306/

相关文章:

c# - 如何读取ANSI编码非英文字母的文本文件?

c# - 使用 .NET 的 SOA 架构真实示例

.net - NUnit 断言枚举值包含标志

php - 如何使用 php 和 mysql Ajax、Jsone 显示公司详细信息的自动显示详细信息

javascript - 尝试从 HTTPS 网站的 HTTP 服务器检索 JSONP

java - 从 POF 流读取数组

jackson - Jackson:将字符串数组反序列化为List <T>

c# - 检查MySQL数据库中是否已经存在一行?

Node.js 的 Json 解析问题

c# - 序列化/反序列化不同的属性名称?