Click here to Skip to main content
15,886,199 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
i want to generate a json file in which data is in this format
XML
var JSON = {
    menu: [
        {id: '0',sub: [
            {name: 'lorem ipsum 0-0',link: '0-0', sub: null},
            {name: 'lorem ipsum 0-1',link: '0-1', sub: null},
            {name: 'lorem ipsum 0-2',link: '0-2', sub: null}
            ]
        },
        {id: '1',sub: null},
        {id: '2',sub: [
            {name: 'lorem ipsum 2-2',link: '2-2', sub: [
                {name: 'lorem ipsum 2-2-0',link: '2-2-0', sub: null},
                {name: 'lorem ipsum 2-2-1',link: '2-2-1', sub: null},
                {name: 'lorem ipsum 2-2-2',link: '2-2-2', sub: null}                
            ]},
            ]
        },
    ]
}

id comes from one table and name, link comes from another table of same database

i m not able to get proper queries to get json file this way

also m using newtonsoft json in asp.net4.0
Posted
Updated 16-May-14 21:47pm
v2

1 solution

Create class in server side as below;

C#
[DataContract]
class MainMenu{
[DataMember]
public int id;

[DataMember]
public SubMenu[] sub;
}

[DataContract]
class SubMenu
{
[DataMember]
public string name;

[DataMember]
public string link;

[DataMember]
public SubMenu[] sub;
}


Now you need to create an array of MainMenu and populate them as per the information in the tables.
MainMenu[] oMainMenues;

Then you could return the oMainMenues as JSON object from Controller class if you use MVC.

If you want create a file anyway or want to return as customer string to form the JSon object in the client side; you could use the JSon serializer as following way.

C#
MemoryStream stream1 = new MemoryStream();
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(MainMenu[]));
ser.WriteObject(YourStream, oMainMenues);


You could refer to followinf article for more related information;
How to: Serialize and Deserialize JSON Data[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900