I am converting data from database into jSon as following with ASP.NET Web Api
:
public string GetData(string userId)
{
var settings = new JsonSerializerSettings
{
ContractResolver = new DefaultContractResolver()
};
string Query = "select USER_ID UserId, USER_NAME UserName from Table where USER_ID = '" userId "'";
DataTable dt = SelectData(Query);
string jSonResult;
jSonResult = JsonConvert.SerializeObject(dt, settings);
return jSonResult;
}
In the project's web api config file, it has the following setting:
public static void Register(HttpConfiguration config)
{
EnableCorsAttribute cors = new EnableCorsAttribute("*", "*", "GET, POST");
config.EnableCors(cors);
//Web api routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
GlobalConfiguration.Configuration.Formatters.Clear();
GlobalConfiguration.Configuration.Formatters.Add(new System.Net.Http.Formatting.JsonMediaTypeFormatter());
}
It returns me the expected jSon data but the issue is the data returned with properties turns into uppercase as follows:
[
{
"USERID": "1002",
"USERNAME": "John"
}
]
Though I used a formatter to keep it default but it returns the above. Any way I can return the properties as below:
[
{
"UserId": "1002",
"UserName": "John"
}
]
CodePudding user response:
In the JsonSerializerSettings
replace the ContractResolver = new DefaultContractResolver()
into
ContractResolver = new CamelCasePropertyNamesContractResolver()
for example
var settings = new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver()
};
CodePudding user response:
public static string GetData(string userId)
{
DataTable dt = new DataTable();
dt.Columns.Add("UserID", typeof(int));
dt.Columns.Add("UserName", typeof(string));
//Some dummy data
dt.Rows.Add(1, "Townsend");
dt.Rows.Add(2, "Marget");
dt.Rows.Add(3, "Deva");
dt.Rows.Add(4, "Aurthur");
var settings = new JsonSerializerSettings
{
ContractResolver = new DefaultContractResolver()
};
string jSonResult;
jSonResult = JsonConvert.SerializeObject(dt);
return jSonResult;
}
It will return the following result
[
{
"UserID": 1,
"UserName": "Townsend"
},
{
"UserID": 2,
"UserName": "Marget"
},
{
"UserID": 3,
"UserName": "Deva"
},
{
"UserID": 4,
"UserName": "Aurthur"
}
]