简体   繁体   中英

JavaScriptSerializer Serialize for Nested Object in c#

I have created class for multi level menu. It works good. But now I want Menu class to convert to JSON object for using in angularjs.

I have class two class

class Menu
{
    private List<Item> Items = new List<Item>();
}

class Item
{
    public int Id { get; set; }
    public int Level { get; set; }
    public string Title { get; set; }
    public string NavigateUrl { get; set; }
    public Menu Child { get; set; }
}`

I need to create JSON object of Menu where Menu class contain List of Item and Item class contain Menu.

JavaScriptSerializer.Serialize work with only one level. Do I have to implement any kind of interface or change the class where serialization is possible?

Your main problem appears to be that your Menu class has an internal, private variable that holds the list of Item objects, and that list isn't accessible by external code.

The Javascript serialiser can only serialise public properties on a class.

If you make your Menu items publicly accessible using a property getter ... something like this:

class Menu
{
    private List<Item> _items = new List<Item>();

    public List<Item> Items
    {
        get { return _items; }
        set { _items = value; }
    }
}

It should work.

Your Item class is already made up of public properties, so that should serialise without a problem.

If I understand your question, you need to do next:

[DataContract]
public class Menu
{
    [DataMember]
    private List<Item> Items = new List<Item>();
}

[DataContract]
public class Item
{
    [DataMember]
    public int Id { get; set; }

    [DataMember]
    public int Level { get; set; }

    [DataMember]
    public string Title { get; set; }

    [DataMember]
    public string NavigateUrl { get; set; }

    [DataMember]
    public Menu Child { get; set; }
}

And after it you can use:

var menu = new Menu(); 
/* add items */ 
var serializer = new JavaScriptSerializer(); 
var serializedResult = serializer.Serialize(menu);

Correct me if I wrong somewhere

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM