简体   繁体   中英

JSON format in asp.net web api

In ASP.NET Web API, I return json as

[{"EmpID":"20160636","FullName":"Md Delower Hossain"}]

But I want that as the following:

{"EmpID":"20160636","FullName":"Md Delower Hossain"}

The parenthesis [] should be omitted for my programming purpose. What can I do?

Instead of returning a collection from your Web API endpoint, you could return a single element:

[HttpGet]
[Route("api/employees")]
public IHttpActionResult Index()
{
    IEnumerable<Employee> employees = ...

    Employee employee = employees.FirstOrDefault();
    return this.Ok(employee);
}

Since you do not provide any code in your question I assume that you return any kind of collection object which gets serialized to JSON in array form.

If you want to return just a single object basically exactly what you need to do in order to achieve that is to return a single object. If your type is called Employee, just return a single instance of Employee from the controller method.

You have to trim the parenthesis.

stringcurrentJson ="[{"EmpID":"20160636","FullName":"Md Delower Hossain"}]";
var ExpectedJson= JObject.Parse(currentJson .Trim(new char[] { '[', ']' }));

then u can use the ExpectedJson wherever u want

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM