Home > Back-end >  Datatable to json - c#
Datatable to json - c#

Time:05-03

I have a data table like below

Subject Question Qtype
English xxxxxxx Subjective
English yyyyyyy Subjective
English zzzzzzz Objective
English sasasas Objective
English cvcvcvv Subjective

Question column will contain the question in text format.

Json should be

{
    "Subject":"English",
    "xxxxxxx":"Subjective",
    "yyyyyyy":"Subjective",
    "zzzzzzz":"Objective",
    "sasasas":"Objective",
    "cvcvcvv":"Subjective"
}

I have tried like below. But this will not return above output.

var list = new List<string[]>();
foreach (DataRow row in dt_questions.Rows)
{
    string Subject   = row["Subject"].ToString();
    string Question= row["Question"].ToString();
    string Qtype= row["Qtype"].ToString();
    list.Add(new string[] { Subject, Question, Qtype});
}
var jsonSerialiser = new JavaScriptSerializer();
var json = jsonSerialiser.Serialize(list);

CodePudding user response:

Since the 'subject' should be used only once, you have to treat this outside the loop, and loop over the rest.
Then use a dictionary instead of a list:

var dt = new DataTable();
foreach(string c in "Subject,Question,Qtype".Split(','))
    dt.Columns.Add(c, typeof(string));
    
for(int i = 1; i<= 5;i  )
    dt.Rows.Add("English", $"Q{i}", (i==3 || i==4 ? "Objective" : "Subjective"));   

var dc = new Dictionary<string, string>();

dc.Add("Subject", dt.Rows[0].Field<string>("Subject"));

foreach(DataRow r in dt.Rows)
{
    dc.Add(r.Field<string>("Question"), r.Field<string>("QType"));
}

var jsonSerialiser = new JavaScriptSerializer();
var json = jsonSerialiser.Serialize(dc);

Or with Newtonsoft:

string json2 = Newtonsoft.Json.JsonConvert.SerializeObject(dc);
  • Related