使用C#反序列化嵌套HTML元素的JSon

时间:2012-06-26 07:22:33

标签: c# json

我使用了this有用的JQuery函数来序列化嵌套元素。问题是如何使用c#对其进行反序列化。

以下代码给出了

没有为'System.Collections.Generic.IList`

的类型定义无参数构造函数
string json = @"{""root"":{""id"":""main"",""text"":""150px"",""children"":
    [{""id"":""divcls"",""text"":""50px"",""children"":
    [{""id"":""qs1"",""text"":""0px"",""children"":[]}]},
     {""id"":""divcls2"",""text"":""50px"",""children"":[]},
     {""id"":""divcls3"",""text"":""50px"",""children"":[]}]}}";

IList<Commn.main1> objs = new JavaScriptSerializer()
    .Deserialize<IList<Commn.main1>>(json);
string blky = "";

foreach (var item in objs)
{
    blky += item.id;
}
Label1.Text = Convert.ToString(blky);

public class main1
{
    public string id { get; set; }
    public string text { get; set; }
    public sub1 children { get; set; }
}

public class sub1
{
    public string Qid { get; set; }
    public string Qval { get; set; }
}

我的Json只有2级深度如果解决方案是递归的,我怎么知道元素的深度

顺便说一下,类可以像这样引用自己

public class main1
{
    public string id { get; set; }
    public string text { get; set; }
    public  main1 children { get; set; }
}

1 个答案:

答案 0 :(得分:1)

首先,是的,一个类可以引用自己。在您的情况下,您需要有一个main1 []属性来表示其子项。

public class main1 
{    
    public string id { get; set; } 
    public string text { get; set; }
    public main1[] children { get; set; } 
}

接下来,您的json字符串不仅包含main1对象,还包含其他具有main1类型的“root”属性的对象。这很好,但是你需要另一个类来反序列化:

public class foo
{
    public main1 root { get; set; }
}

然后,您应该能够使用Deserialize方法获取foo的实例:

var myFoo = new JavaScriptSerializer().Deserialize<foo>(json);