Reputation: 163
I've used this useful JQuery function that serializes nested elements. the problem is how to deserialise it using c#.
the following code gives
No parameterless constructor defined for type of '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; }
}
My Json is only 2 Levels deeep If the solution is recursive how could i know the depth of the element
By the way can a class reference itself like this
public class main1
{
public string id { get; set; }
public string text { get; set; }
public main1 children { get; set; }
}
Upvotes: 1
Views: 289
Reputation: 1396
First of all, yes a class can reference itself. In your case, you would need to have a main1[] property to represent its children.
public class main1
{
public string id { get; set; }
public string text { get; set; }
public main1[] children { get; set; }
}
Next, your json string contains not only a main1 object, but also some other object with a "root" property of type main1. It's perfectly fine, but then you need another class to deserialize into :
public class foo
{
public main1 root { get; set; }
}
You should then be able to use the Deserialize method to get an instance of foo :
var myFoo = new JavaScriptSerializer().Deserialize<foo>(json);
Upvotes: 1