Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Give a name to an array of JSON objects

I am new to JSON and i am trying to get data from database in Sql Server with Asp.net Web Api.

My Output json Array is Like this:

[ { "f0": 9608, "f1": 1461, "frbDescField_F56": "Jan", "f2": "1461", "f3": "179:48"}]

But the output of the Json should be similar to the following code:

{ "restaurants": [ { "f0": 9608, "f1": 1461, "frbDescField_F56": "Jan", "f2": "1461", "f3": "179:48"}] }

and My Code is:

public IEnumerable<VI_TimeTotalMontly> Get(int id, string id1)
{
    using (tfmisEntities Entities = new tfmisEntities())
    {
        var result = Entities.VI_TimeTotalMontly.Where(e => e.F0 == id && e.F2 == id1).ToList();
        return result;
    }
}

How do I change my codes?

like image 642
GodFather Avatar asked Mar 07 '23 13:03

GodFather


2 Answers

You can build a strongly typed anonymous object to match the desired output. You would also need to change the return type of the action as IEnumerable<VI_TimeTotalMontly> would just return a collection, when you want an object response

public IHttpActionResult Get(int id, string id1) {
    using (var Entities = new tfmisEntities()) {
        var restaurants = Entities.VI_TimeTotalMontly
                              .Where(e => e.F0 == id && e.F2 == id1)
                              .ToList();

        var result = new {
            restaurants = restaurants;
        };

        return Ok(result);
    }
}
like image 120
Nkosi Avatar answered Mar 10 '23 13:03

Nkosi


I would use a dynamic object to wrap your result:

dynamic output = new ExpandoObject();
output.restaurants = result;

return output;
like image 20
hardkoded Avatar answered Mar 10 '23 13:03

hardkoded