nul*_*ble 19 .net json deserialization
可能重复:将
JSON反序列化为多个C#子类之一
我有遵循JSON模式的只读访问:
{ items: [{ type: "cat", catName: "tom" }, { type: "dog", dogName: "fluffy" }] }
Run Code Online (Sandbox Code Playgroud)
我想将其中的每一个反序列化为各自的类型:
class Cat : Animal {
string Name { get; set; }
}
class Dog : Animal {
string Name { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
我唯一想到的是将它们反序列化为一个dynamic对象,或者Dictionary<string, object>然后从那里构造这些对象.
我可能会遗漏一些JSON框架中的内容....
你的方法是什么?=]
nic*_*k_w 35
我想你可能需要反序列化Json然后从那里构造对象.直接反序列化Cat或Dog不可能反序列化,因为反序列化器不会专门知道如何构造这些对象.
编辑:大量借鉴使用JSON.NET将异构JSON数组反序列化为协变List <>
像这样的东西会起作用:
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());
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9496 次 |
| 最近记录: |