I have created an ASP.NET Web API 2 and I tried to show data in json format, it shows in horizontal way and it look like this in google chrome. I want to make it in the expect format.
Below error is what I get in the Google chrome:
This XML file does not appear to have any style information associated with it. The document tree is shown below. [{"UserId":23,"Name":"Emily","Access":3,"Mobile":"07419231"},{"UserId":31,"Name":"Lydia","Access":5,"Mobile":"67567587"},{"UserId":45,"Name":"Peter","Access":1,"Mobile":"90345853"},{"UserId":56,"Name":"Lebron","Access":4,"Mobile":"43895449"},{"UserId":73,"Name":"Amber","Access":0,"Mobile":"45788477"}]
What I expect is something like this format in below:
[
{
"UserId":23,
"Name":"Emily",
"Access":3,
"Mobile":"07419231"
},
{
"UserId":31,
"Name":"Lydia",
"Access":5,
"Mobile":"67567587"
},
{
"UserId":45,
"Name":"Peter",
"Access":1,
"Mobile":"90345853"
},
{
"UserId":56,
"Name":"Lebron",
"Access":4,
"Mobile":"43895449"
},
{
"UserId":73,
"Name":"Amber",
"Access":0,
"Mobile":
"45788477"
}
]
Here is my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Data;
using System.Data.SqlClient;
using Newtonsoft.Json;
namespace ApiTesting.Controllers
{
public class TestController : ApiController
{
SqlConnection con = new SqlConnection(@"server=DESKTOP-US2AF5N; database=Test; integrated security=true;");
public string Get()
{
SqlDataAdapter da = new SqlDataAdapter("Select * From TblDraft", con);
DataTable dt = new DataTable();
da.Fill(dt);
if (dt.Rows.Count > 0)
{
return JsonConvert.SerializeObject(dt);
}
else
{
return "No Data Found";
}
}
}
}
When you serialize an c# object using Newtonsoft.Json you have to add a formatting option if you want to get an intented string
return JsonConvert.SerializeObject(dt,Newtonsoft.Json.Formatting.Indented);