C#
===
using System;
using System.Collections.Generic;
using System.Web.Script.Serialization;
using System.Data;
using System.Text;
namespace TESTConsoleApplicatio
{
public class JSONCLASS
{
public static string GetJSONData(DataTable dt)
{
StringBuilder sb = new StringBuilder();
List
foreach (DataRow dr in dt.Rows)
{
Dictionary
for (int i = 0; i < dt.Columns.Count; i++)
{
drow.Add(dt.Columns[i].ColumnName, dr[i]);
}
result.Add(drow);
}
JavaScriptSerializer js = new JavaScriptSerializer();
string jsonString = js.Serialize(result);
//OUTPUT JSON
//{"product":[{\"ID\":1001,\"name\":\"Book 1\",\"category\":\"Category 1\"},
// {\"ID\":2001,\"name\":\"Book 2\",\"category\":\"Category 2\"},
// {\"ID\":1002,\"name\":\"Book 22\",\"category\":\"Category 1\"} ]}
return "{\"" + dt.TableName + "\":" + jsonString + "}";
}
}
}
========
INPUT/OUTPUT
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
namespace TESTConsoleApplicatio
{
class Program
{
static void Main(string[] args)
{
//INPUT DATA.May be we can get data from database or other sources
DataTable dt = new DataTable("product");
dt.Columns.Add("ID",typeof( int));
dt.Columns.Add("name");
dt.Columns.Add("category");
DataRow rw = dt.NewRow();
rw["ID"] = 1001;
rw["name"] = "Book 1";
rw["category"] = "Category 1";
dt.Rows.Add(rw);
rw = dt.NewRow();
rw["ID"] = 2001;
rw["name"] = "Book 2";
rw["category"] = "Category 2";
dt.Rows.Add(rw);
rw = dt.NewRow();
rw["ID"] = 1002;
rw["name"] = "Book 22";
rw["category"] = "Category 1";
dt.Rows.Add(rw);
string jsonOutput = JSONCLASS.GetJSONData(dt);
//We can out put data as a web services
Console.Write(jsonOutput);
Console.ReadLine();
}
}
}
No comments:
Post a Comment