Johan
Johan

Reputation: 35194

Nested JSON-object in c#

I want to create a multidimensional json object based on a c# class. I normally do it like this:

public class foo
{
    public string name { get; set; }
    public int age { get; set; }
}

And serialize a new instance of the class with a JavaScriptSerializer. But lets say that i want to add another json array containing the persons friends inside the main json array. Example array: Accessing data in a multidimensional JSON array with jQuery

Hope you get the idea. Thanks

Upvotes: 0

Views: 2495

Answers (2)

christofr
christofr

Reputation: 2700

How are you creating the JSON version of your class, foo?

JavaScriptSerializer and Controller.JSON (in MVC) support serializing IEnumerable derived types, so you could have the class:

public class foo
{
    public string name { get; set; }
    public int age { get; set; }
    public List<Bar> friends {get; set;}
}

and your JSON serialized class would include the list of Bar objects.

Upvotes: 0

Yves M.
Yves M.

Reputation: 3318

If I get your question corect, something like this should work...

public class Person 
{     
  public string name { get; set; }     
  public int age { get; set; } 
  public List<Person> Friends { get; set; }
} 

Upvotes: 1

Related Questions