简体   繁体   中英

How to return Complex Json Object from C# DataTable

We currently use Newtonsoft.Json to convert a datatable to a json stream.

If my datatable includes the following:

Name    Sales
Joe     10
Mary    20

then the following code will return [{"Name": "Joe", "Sales":10},{"Name": "Mary", "Sales":20}] which is great:

 string callback = JsonConvert.SerializeObject(table);
 byte[] resultBytes = Encoding.UTF8.GetBytes(callback);
 return new System.IO.MemoryStream(resultBytes);

But there are times that I need a more complex json stream. Something like this:

{ "map": "USA", "areas":[{"Name": "Joe", "Sales":10},{"Name": "Mary", "Sales":20}]}

The json now includes an extra tuple { "map": "USA", "areas": , and an additional {} .

What does my datatable need to include to get that type of json stream? And what does the C# need to look like?

You would need to define a new class and serialize the entire object like so:

// Define the class / model
public class MyNewClass {
// Case sensitive vvv to match your Json
    public string map {get; set;}
    public DataTable areas {get; set;}
    // you can have several constructor methods defined, I show the usage for each below.
    public MyNewClass() {}
    public MyNewClass(string countryMap, DataTable table) {
        map = countryMap;
        areas = table;
    }
}

Usage:

// Instantiate the object from the class / model
var returnData = new MyNewClass("USA", table);
// or
var returnData2 = new MyNewClass();
returnData2.map = "USA";
returnData2.areas = table;

// Finally serialize your object
var yourJson = JsonConvert.SerializeObject(returnData);
// or
var yourJosn2 = JsonConvert.SerializeObject(returnData2);

If you data source is actually a database (and it looks like it is), there are numerous advantages of using POCOs over DataTable.

One of them is the possibility to use an ORM to easily fetch information in a convenient form. Eg EntityFramework .

For your particular complex example, the flow could be the following:

1) Define classes to hold the data

  class Area 
   {
       public string Name { get; set; }
       public int Sales { get; set; }
   }

   class Map 
   {
       public string Map { get; set; }
       public List<Area> Areas { get; set; }
   }

2) Populate with data from database

3) Serialize Area with JsonConvert.SerializeObject .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM