Reputation: 767
I have a question on a MVC4 (beta) issue I have been struggling with for some time now. The issue is that I want to create a json with the object name added for my webapi. The json has to be created this was as the receiving side needs this. My .NET/MVC knowledge is limited so please bear with me. I tried searching on the subject, but as MVC4 is still in beta it's difficult to find good info on this subject.
I have already imported the JSON.NET formatter in my solution, but this does not add the Object name
The json that is now created in MVC4:
[{"ID":36,"Name":"Test3","Description":"Description Test3"},{"ID": 37,"Name": "Test4","Description": "Description Test4"}]
And I would like the json to look like this:
{"Goal":[{"ID":36,"Name":"Test3","Description":"Description Test3"},{"ID": 37,"Name": "Test4","Description": "Description Test4"}]}
So I like the object name (Goal) to be included in the json.
The code in my api controller I am using for this is:
StoreDBContext db = new StoreDBContext();
//
// GET /api/goals
public IQueryable<Goals> Get()
{
return db.Goals;
}
I assume I need to loop through somewhere to add the object name, but I am not sure how... Hopefully someone can help me out with this!
Upvotes: 4
Views: 1460
Reputation: 7584
Return something like this:
new { Goal = db.Goals().AsEnumerable().ToList() }
You can use an anonymous object to add properties and stuff that aren't in the object.
You can also write custom converters for JSON.NET if you want it to deserialize properly, but if you don't care about deserialization of the output, the above solution will work.
Upvotes: 3