28

重複の可能性:
JSON をいくつかの C# サブクラスの 1 つに逆シリアル化する

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つから何かが欠けている可能性があります....

あなたのアプローチは何ですか?=]

4

1 に答える 1

48

Jsonを逆シリアル化して、そこからオブジェクトを構築する必要があると思います。デシリアライザーはこれらのオブジェクトを具体的に構築する方法を知らないため、直接デシリアライズすることはCatできDogません。

編集JSON.NETを使用して異種JSON配列を共変リスト<>に逆シリアル化することから多額の借用

このようなものが機能します:

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());
于 2012-10-11T07:02:04.463 に答える