4

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?

2 Answers 2

6

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);
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

I would prefer this answer as it does not involve operations during runtime like when we use dynamic. It is better to get things done in compile time. Unless you have no other option try to use this method.
1

I would use a dynamic object to wrap your result:

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

return output;

1 Comment

This is fine but incomplete. You would also need to explain changing the action signature.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.