How to remove first and last square brackets from JSON from query string web api c#

asp.net-web-api2 c# entity-framework-6 json

Question

How to remove only response SQUARE BRACKET FROM result - response: []

public HttpResponseMessage GetDetail(int id)
    {

        var result = new Dictionary<string, object>();
        EDetail EDetailobj = db.EDetails.FirstOrDefault(P => P.DetailID == id);
        if (EDetailobj != null)
        {
            result.Add("Status", "ok");

            var responseResult = db.EDetails
                .Where(x => x.DetailID == id)
                .Select(x => new
                {
                    x.DetailID ,
                    x.DetailName,
                    x.Qty,
                    x.Price,
                });
            result.Add("Response", responseResult);
            return Request.CreateResponse(HttpStatusCode.OK, result);
        }
        else
        {
            result.Add("Status", "failure");
            return Request.CreateResponse(result);
        }
    }

{
  "status": "ok",
  "response": [
    {
      "detailID": 1,
      "detailName": "whiteshirt",
      "qty": 12,
      "price": 21.0,
    }
  ]
}
1
0
2/1/2018 10:05:50 PM

Popular Answer

In your DB query, you're returning a list of results that match the query x.DetailID == id. True, there's probably only one result in it, but that doesn't change the fact that Where always returns a collection, not a single object.

So now you're returning, as part of your result, as list containing a single item. This list is serialized into JSON exactly as you see it - as a JSON Array (the square brackets) containing a single object.

If you want to avoid that, don't return a collection - return a single object:

var responseResult = db.EDetails
            .Where(x => x.DetailID == id)
            .Select(x => new
            {
                x.DetailID ,
                x.DetailName,
                x.Qty,
                x.Price,
            })
            .SingleOrDefault();
2
2/1/2018 11:30:26 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow