I want to return JSON format from my database using asp.net mvc5 c#. I tried a lot of ways but was unable to generate data as per my requirement. I need the JSON array in this format.
{
"draw":0,
"recordsTotal":2,
"recordsFiltered":2,
"data":[
[
"126",
"Test Name 1",
"07.01.2022 11:55 AM",
"Male"
],
[
"127",
"Test Name 2",
"01.02.2022 11:55 AM",
"Male"
]
]
}
Instead of this I am getting output in given format
{
"draw":0,
"recordsTotal":2,
"recordsFiltered":2,
"data":[
{
"ID":126,
"Name":"Test Name 1",
"Date":"07.01.2022 11:55 AM",
"Gender":"Male"
},
{
"ID":127,
"Name":"Test Name 2",
"Date":"01.02.2022 11:55 AM",
"Gender":"Male"
}
]
}
My ASP.NET MVC5 C# code is below
public ContentResult GetDoctor()
{
var doctors = db.Doctors.Where(e => e.ID > 0);
var doct = doctors.Select(c => new
{
ID = c.ID + "," +
"," + c.Name +
"," + c.Date +
"," + c.Gender
}).ToList();
string students = string.Join("],[", doct.Select(e => e.ID.ToString()));
students = JsonConvert.SerializeObject(students);
JsonSerializerSettings hg = new JsonSerializerSettings();
hg.Formatting = Formatting.Indented;
hg.TypeNameHandling = TypeNameHandling.None;
string json = JsonConvert.SerializeObject(doctors.ToList(),hg);
return Content(json.ToString(), "application/json");
}
2
Answers
You can use the following method:
Get draw values from UI. like this :
The doctors is your list.
The value of the record number is also obtained from the number of data in the list.
With this answer, you can send your data to the UI and load it into the datatable.
I use this standard in my projects and it works.
If you need to use strictly the first structure to return data, then the output structure must be:
Then I suposse the data you recover from database is in the second format:
So you need to transform your data into the required result format data and deserialize