Robert_Junior
Robert_Junior

Reputation: 1123

Creating JSon in asp.net?

I am very new to ASP.net . How could I create the following JSON object in c#

{"total":2,"rows":[{"productid":"1","attr":{"size":"10dc","color":"red&yellow"},
                    {"productid":"2","attr":{"size":"102dc","color":"green&white"}

My ultimate aim is to send this JSON Object to client side data gird for data binding.The grid is expecting the data in this format

Upvotes: 1

Views: 165

Answers (1)

John Koerner
John Koerner

Reputation: 38077

JSON.Net is an easy way to do this, to create the output in your example, define your class structure:

public class DefaultObject
{
    public int total;
    public List<Row> rows;
}
public class Row {
    public string productid;
    public Attribute attr;

}

public class Attribute {
    public string size;
    public string color;
}

Then create an instance and serialize it:

List<Row> Rows = new List<Row>();
Rows.Add(new Row() { productid="1", attr = new Attribute() { color = "red&yellow", size = "10dc"}});
Rows.Add(new Row() { productid="2", attr = new Attribute() { color = "green&white", size = "102dc"}});
DefaultObject obj = new DefaultObject { total = 2, rows = Rows};

Debug.WriteLine(Newtonsoft.Json.JsonConvert.SerializeObject(obj));

Upvotes: 1

Related Questions