1

Possible Duplicate:
How to create JSON string in C#

I want to use google chart in mt ASP.NET MVC application. There is no mvc examples in there and datatable struct. I have never worked Json before and I must create a json like following code.

How can I create like this in C#

{"cols":[
  {"id":"","label":"Month","pattern":"","type":"string"},
  {"id":"","label":"Sales","pattern":"","type":"number"},
  {"id":"","label":"Expenses","pattern":"","type":"number"}],
"rows":[
  {"c":[
    {"v":"April","f":null},
    {"v":1000,"f":null},
    {"v":900,"f":null},
  {"c":[
    {"v":"July","f":null},
    {"v":1030,"f":null},
    {"v":null,"f":null},
"p":null
}

I cant find easy examples about creating json in C#. Please Help me.

Thanks.

Community
  • 1
  • 1
AliRıza Adıyahşi
  • 15,658
  • 24
  • 115
  • 197

6 Answers6

3

Give Json.NET a try. I think it will give you what you need.

Miklar
  • 31
  • 1
  • 3
2

Create it as a normal class with properties, then:

var json = new JavaScriptSerializer().Serialize(myObject)

or a dynamic object:

var json = new JavaScriptSerializer().Serialize(new { property = "string" })
paulslater19
  • 5,869
  • 1
  • 28
  • 25
2

Follow a nice article about this on code project

http://www.codeproject.com/Articles/78928/Create-JSON-from-C-using-JSON-Library

Usman
  • 3,200
  • 3
  • 28
  • 47
0

Well you can use DataContractJsonSerializer Class to Serializes objects to the JavaScript Object Notation (JSON) and deserializes JSON data to objects. in .net 4.0.

I hope you have checked How to create JSON string in C# and this is not duplication of the same.

Apart from that you can have option to use WCF services that produce RESTful Service and JSON data. You can check this example that is best example to suit your needs in WCF.

Another approach is if you like some built in library then Json.Net is one of the good library around on codeplex.

Community
  • 1
  • 1
Jigar Pandya
  • 6,004
  • 2
  • 27
  • 45
0

I would try the JSON.NET library. It has advantages of most of the serializers built into .NET in terms of both capability and performance. And I believe Microsoft will be bundling the JSON.NET library with ASP.NET 4.5 as a result.

David
  • 2,226
  • 32
  • 39
0

Have a look at this code.

    var oSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
    oSerializer.MaxJsonLength = int.MaxValue;
    string sa = oSerializer.Serialize(p); // where p is your object to serialize.

    sa = "{ \"Result\": " + sa + " }";