将JSON反序列化为多个C#子类之一 [英] Deserializing JSON into one of several C# subclasses

查看:1293
本文介绍了将JSON反序列化为多个C#子类之一的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的json结构看起来像这样:

I have a json structure that looks something like this:

"list":[
  {
    "type":"link",
    "href":"http://google.com"
  },
  {
    "type":"image",
    "src":"http://google.com/logo.png"
  },
  {
    "type":"text",
    "text":"some text here"
  },
]

我想要将其反序列化为对象列表,其中每个对象都是基类的子类。列表中的每个项目都有不同的属性(href,src,text),因此我不能使用相同的类来获取一个。相反,我想要一个普通类的三个子类。 JSON列表中每个项的type属性可用于决定使用哪个子类。例如,我可以拥有以下类

I would like to deserialize this into a list of objects, where each object is a subclass of a base class. Each item in the list has different properties (href, src, text), so I can't use the same class for reach one. Instead I would like three subclasses of a general class. The type property of each item in the JSON list can be used to decide which subclass to use. So for example, I could have the following classes

public Item{
  public string type {get; set;}
}
public LinkItem : Item {
  public string href {get; set;}
}
public ImageItem : Item {
  public string src {get; set;}
}
public TextItem : Item {
  public string text {get; set;}
}

有没有办法做到这一点?或者有更好的方法来反序列化异构对象类型列表吗?

Is there any way to do this? Or is there a better way to deserialize a list of heterogeneous object types?

编辑:

我顺便使用json.net

I am using json.net by the way

推荐答案

正如@AmithGeorge建议的那样,您可以使用动态对象来动态解析您的json对象。您可以使用 Shawn Weisfeld的JSON动态类此处是他的博客解释他是如何做的

As @AmithGeorge suggested, you can use a dynamic object to dynamically parse your json object. You can use this great dynamic class for JSON by Shawn Weisfeld. Here is his blog explaining how he do it.

JavaScriptSerializer jss = new JavaScriptSerializer();
jss.RegisterConverters(new JavaScriptConverter[] { new DynamicJsonConverter() });

dynamic glossaryEntry = jss.Deserialize(json, typeof(object)) as dynamic;

Console.WriteLine("glossaryEntry.glossary.title: " + glossaryEntry.glossary.title);
Console.WriteLine("glossaryEntry.glossary.GlossDiv.title: " + glossaryEntry.glossary.GlossDiv.title);
Console.WriteLine("glossaryEntry.glossary.GlossDiv.GlossList.GlossEntry.ID: " + glossaryEntry.glossary.GlossDiv.GlossList.GlossEntry.ID);
Console.WriteLine("glossaryEntry.glossary.GlossDiv.GlossList.GlossEntry.GlossDef.para: " + glossaryEntry.glossary.GlossDiv.GlossList.GlossEntry.GlossDef.para);
foreach (var also in glossaryEntry.glossary.GlossDiv.GlossList.GlossEntry.GlossDef.GlossSeeAlso)
{
    Console.WriteLine("glossaryEntry.glossary.GlossDiv.GlossList.GlossEntry.GlossDef.GlossSeeAlso: " + also);
}

这篇关于将JSON反序列化为多个C#子类之一的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆