0

I have a list of Departments and would like to show them inside a treeview. Im using C#, ASP.NET. I found this cool control called Treed http://bl.ocks.org/mbostock/raw/4339083/dd87a364df6d921740af7e5badef247665918919/ however it requires a JSON file.

What would be the best possible way to achieve this kind of JSON structure from ASP.net? http://bl.ocks.org/mbostock/raw/4063550/flare.json

Currently I store this data as a DataTable. If there's a solution through any other collection please do advice as Im open to anything at this point.

Many Thanks for your help.

user1203996
  • 89
  • 1
  • 11
  • Did you *try* searching for [data table conversions to json](http://stackoverflow.com/questions/2312982/from-datatable-in-c-sharp-net-to-json)? – crthompson Mar 16 '15 at 17:58
  • 1
    possible duplicate of [how to convert datatable to json in C#](http://stackoverflow.com/questions/17398019/how-to-convert-datatable-to-json-in-c-sharp) – cheesemacfly Mar 16 '15 at 18:29

2 Answers2

0

First off, there are a couple of built-in serializers. You can use WCF DataContracts and the DataContractJsonSerializer to produce JSON data designed for consumption by your service endpoints. If your application uses a lot of WCF in its service architecture anyway, this serializer should be easy enough to incorporate.

There is also a JavaScriptSerializer class in System.Web.Script.Serialization; it has a less aspect-oriented customization scheme, requiring you to define a custom converter class if the serializer can't understand your class (or its default behavior isn't what you want), but given you control both the production and consumption of this JSON data and so you can theoretically adapt the client-side scripting to deal with the default behavior, overall this is probably the simplest way to turn an object into JSON.

Lastly, there's a third-party library, JSON.NET, available at http://www.newtonsoft.com/json. It's pretty good; I've used it in a few projects for JSON results of AJAX-y ScriptMethods. It has attributes you can use to make small customizations to serialization behavior, without the full weight of WCF DataContracts.

KeithS
  • 70,210
  • 21
  • 112
  • 164
-2

Have you considered this example:

Product product = new Product();
product.Name = "Apple";
product.Expiry = new DateTime(2008, 12, 28);
product.Sizes = new string[] { "Small" };

string json = JsonConvert.SerializeObject(product);
// {
//   "Name": "Apple",
//   "Expiry": "2008-12-28T00:00:00",
//   "Sizes": [
//     "Small"
//   ]
// }

Here are some links to consider:

This link lets you generate c# classes with JSON:

http://json2csharp.com/

This link supports classes to JSON

http://www.json.net

Scott Nimrod
  • 11,206
  • 11
  • 54
  • 118