Reputation: 16239
I have following simple code which is giving list of employee , i have not added any formatter
getting result in json array
format.
I want it as a json object which has one defined key , how can i achieve this?
public HttpResponseMessage GetEmployee([FromUri(Name ="")]FilterEntity filters)
{
try
{
string contentType=Request.Headers.Accept.ToString();
if (String.Equals(contentType, Ecng_APIMsg.ContentType))
{
var empDetails = _empService.GetEMployee(filters.systemId, filters.pageIndex, filters.pageSize, filters.sortDirection);
if (empDetails != null)
{
return Request.CreateResponse(HttpStatusCode.OK, empDetails);
}
}
}
catch(Exception ex)
{
}
}
output-
[
{
"Id": 43,
"EmpId": 11
},
{
"Id": 42,
"EmpId": 12
}
]
expected
"data" : [
{
"Id": 43,
"EmpId": 11
},
{
"Id": 42,
"EmpId": 12
}
]
data
must be there as a key of that json object.
I tried like below code to achieve this which is not working I'm missing something here -
var response = Request.CreateResponse(HttpStatusCode.OK, empDetails);
response.Content = new StringContent(response.ToString(), System.Text.Encoding.UTF8, "application/json");
return response;
Upvotes: 0
Views: 110
Reputation: 247531
You could create an object to wrap the collection. Using an anonymous object can be done as a quick and simple solution.
return Request.CreateResponse(HttpStatusCode.OK, new { data = empDetails });
Based on original example in question the above update to the code would yield
{
"data" : [
{
"Id": 43,
"EmpId": 11
},
{
"Id": 42,
"EmpId": 12
}
]
}
Upvotes: 0
Reputation: 91
public class clsDemo
{
public Object data { get; set; }
}
clsDemo ObjDemo = new clsDemo();
ObjDemo.data = empList;//Your 'empDetails'
String result = JsonConvert.SerializeObject(ObjDemo);
Upvotes: 1
Reputation: 4638
Hope in your code "var empDetails
" is a List<Employee>
(List of Employee class)
As per your JSON structure i guess your Employee class would be like below
public class Employee
{
public int Id{ get; set; }
public int EmpId{ get; set; }
}
That's the reason when you are returning the json structure, it returns as
[
{
"Id": 43,
"EmpId": 11
},
{
"Id": 42,
"EmpId": 12
}
]
if you want your json data need to be changed as you expect, then create another class named as EmployeeVM
public class EmployeeVM
{
public List<Employee> data{ get; set; }
}
and construct your EmployeeVM from your code and return EmployeeVM as json from your web api.
Upvotes: 1