4

i am trying to mimic an example where they are using hard coded JSON

{
"page": 1,
"total": 1,
"records": 2,
"rows": [
   {"id": 1, "cell": ["1", "Super Item", "300", 0, null, false, false]},
       {"id": 2, "cell": ["2", "Item 1", "100", 1, 1, false, false]},
       {"id": 3, "cell": ["3", "Sub Item 1", "50", 2, 2, true, true]},
       {"id": 4, "cell": ["4", "Sub Item 2", "25", 2, 2, false, false]},
       {"id": 5, "cell": ["5", "Sub-sub Item 1", "25", 3, 4, true, true]},
       {"id": 6, "cell": ["6", "Sub Item 3", "25", 2, 2, true, true]},
       {"id": 7, "cell": ["7", "Item 2", "200", 1, 1, false, false]},
       {"id": 8, "cell": ["8", "Sub Item 1", "100", 2, 7, false, false]},
       {"id": 9, "cell": ["9", "Sub-sub Item 1", "50", 3, 8, true, true]},
       {"id": 10, "cell": ["10", "Sub-sub Item 2", "50", 3, 8, true, true]},
       {"id": 11, "cell": ["11", "Sub Item 2", "100", 2, 7, true, true]}
    ]
} 

but i need to generate this from C#. Are there any suggestions for the best way to go about generating this above in C#?

Kirill Polishchuk
  • 54,804
  • 11
  • 122
  • 125
leora
  • 188,729
  • 360
  • 878
  • 1,366
  • 2
    `DataContractJsonSerializer` (built in) or Json.net – CodesInChaos Jun 28 '11 at 12:39
  • It seems to me that the answer depend on more information. For example, do you use ASP.NET MVC, WFC or ASMX web services for example. Which .NET version you use? – Oleg Jun 28 '11 at 12:40
  • @Oleg - this is for MVC as i am trying to play around with jqgrid Treegrid. Do you have any example of treegrid and asp.net-mvc (given you are the expert :) ) – leora Jun 28 '11 at 12:50
  • I used tree grid mostly with local data. In case of remote data you should just produce data which has values for additional hidden columns. see [the answer](http://stackoverflow.com/questions/5322608/jqgrid-tree-view-adjacencey/5333199#5333199) and [here](http://stackoverflow.com/questions/5862336/jqgrid-autoloading-treegrid-issue/5867537#5867537). It is important to understand the meaning of `loaded` column and to understand that **paging is not supported by jqGrid tree grid**. – Oleg Jun 28 '11 at 13:30
  • Look at [Json.NET](http://json.codeplex.com/) – Kirill Polishchuk Jun 28 '11 at 12:37

4 Answers4

11

The Controller class has a Json method that serialises objects as JSON, so in your action method you just create the object and call the method:

public ActionResult GetData() {
  return Json(
    new {
      page = 1,
      total = 1,
      records = 2,
      rows = new[] {
        new { id = 1, cell = new object[] { "1", "Super Item", "300", 0, null, false, false } },
        new { id = 2, cell = new object[] { "2", "Item 1", "100", 1, 1, false, false } },
        new { id = 3, cell = new object[] { "3", "Sub Item 1", "50", 2, 2, true, true } },
        new { id = 4, cell = new object[] { "4", "Sub Item 2", "25", 2, 2, false, false } },
        new { id = 5, cell = new object[] { "5", "Sub-sub Item 1", "25", 3, 4, true, true } },
        new { id = 6, cell = new object[] { "6", "Sub Item 3", "25", 2, 2, true, true } },
        new { id = 7, cell = new object[] { "7", "Item 2", "200", 1, 1, false, false } },
        new { id = 8, cell = new object[] { "8", "Sub Item 1", "100", 2, 7, false, false } },
        new { id = 9, cell = new object[] { "9", "Sub-sub Item 1", "50", 3, 8, true, true } },
        new { id = 10, cell = new object[] { "10", "Sub-sub Item 2", "50", 3, 8, true, true } },
        new { id = 11, cell = new object[] { "11", "Sub Item 2", "100", 2, 7, true, true } }
      }
    } 
  );
}
Guffa
  • 687,336
  • 108
  • 737
  • 1,005
  • +! Great for one-off things if creating serializable classes are overkill. Also closest to the JS equivalent . – Davy8 Jun 28 '11 at 13:12
4

There's a class built into .Net 2+ which is called 'JavaScriptSerializer' which creates a JSON structured string based on a .Net typed class.

Using the serializer you can simply created a class with properties and collections to represent your JSON data. Create an instance of it in .Net server side code and then respond using the serializer to generate a valid JSON string response.

Here's an example of converting a Person class instance to a serialized JSON string;

JavaScriptSerializer js = new JavaScriptSerializer();
Person p1 = new Person();
p1.firstName = "Brian";
p1.lastName = "Scott";
p1.department = "Microsoft";
p1.address.addressline1 = "Microsoft";
p1.address.addressline2 = "";
p1.address.city = "Redmond";
p1.address.state = "Seattle";
p1.address.country = "America";
p1.address.pin = 560028;
p1.technologies = new string[] { "IIS", "ASP.NET", "JavaScript", "AJAX" };

string strJSON = js.Serialize(p1);

This will produce a valid JSON string of

{"firstName":"Brian","lastName":"Scott","department":"Microsoft","address":{"addressline1":"Microsoft","addressline2":"","city":"Redmond","state":"Seattle","country":"America","pin":560028},"technologies":["IIS","ASP.NET","JavaScript","AJAX"]}

If you are intending to use a webservice to produce the JSON response to the client side then you can mark your method as;

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string GetPersonJSON()
{
    JavaScriptSerializer js = new JavaScriptSerializer();
    Person p1 = new Person();
p1.firstName = "Brian";
p1.lastName = "Scott";
p1.department = "Microsoft";
p1.address.addressline1 = "Microsoft";
p1.address.addressline2 = "";
p1.address.city = "Redmond";
p1.address.state = "Seattle";
p1.address.country = "America";
p1.address.pin = 560028;
p1.technologies = new string[] { "IIS", "ASP.NET", "JavaScript", "AJAX" };

return js.Serialize(p1);
}
Brian Scott
  • 9,221
  • 6
  • 47
  • 68
  • 1
    3.5+, it seems. But still, no external crap required. – cHao Jun 28 '11 at 12:55
  • 1
    Thanks, I thought it was a 2.0+ inclusion but now that I think about it the class did come along with the other System.web.extension classes of 3.0. Cheers. – Brian Scott Jun 28 '11 at 12:56
1

Apparently you are trying to populate a jqGrid and you're using ASP.NET MVC. If you have defined a class for these values:

["1", "Super Item", "300", 0, null, false, false]

You can store all the elements in a collection myCollection
you can do something like this:

var ReturnData = new
    {
        total = totalPages,
        page = page,
        records = totalRecords,
        rows = myCollection.Select(r => new
        {
            id = r.Id.ToString(),
            cell = new String[] { r.Field1, r.Field2, r.Field3, r.Field4 }
        })
        };

return (Json(ReturnData, JsonRequestBehavior.DenyGet));
LeftyX
  • 35,328
  • 21
  • 132
  • 193
0
class Row {
   public int id {get;set;}
   public object[] cell {get;set;}
}

class Data {
  public int page {get;set;}
  public int total {get;set;}
  public int records {get;set;}
  public Row[] rows {get;set;}
}

var myData = new Data(){ .... };
var json =  new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(myData);
rpgmaker
  • 800
  • 1
  • 4
  • 7
  • those classes aren't serializable – harryovers Jun 28 '11 at 13:01
  • They don't need to be serializable. Because this is not using binary serialization or json datacontract. It is using Json Serialization which does not deal with Serializable Attribute – rpgmaker Jun 28 '11 at 21:05