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

时间:2012-10-11 04:38:28

标签: .net json deserialization

  

可能重复:
  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框架......

你的方法是什么? =]

1 个答案:

答案 0 :(得分:31)

我认为你可能需要反序列化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());