1

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?

1
  • Can we see the method you are using to return the JSON? Commented Jan 14, 2015 at 16:36

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. I didn't realized I kept my Items variable private. Although I done that for some other reason.
0

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

1 Comment

I tried your code as well. but with private variable it doesn't work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.