2012-06-26 107 views
1

我已使用this有用的JQuery函数序列化嵌套元素。问题是如何使用c#反序列化它。Deserialise使用C#嵌套HTML元素JSon

下面的代码给出

类型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级别deeep如果解决方案是递归的我怎么能知道元件

深度顺便说可以类引用本身这样

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

回答

1

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

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

接下来,你的JSON字符串不仅包含MAIN1对象,而且还与类型MAIN1的“根”属性某些其他物体。这是完全正常的,但你需要另一个类反序列化到:

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

然后,您应该能够使用反序列化方法来获取FOO的一个实例:

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

非常感谢配音 –