clifford.duke
clifford.duke

Reputation: 4040

Custom Web API Formatting

I've been playing around with asp.net web api, and I noticed that default generated returned json doesn't include the object level key. I was also wondering how to customize the output of the json string. For example:

Getting a User usually returns

{
    "Name": "ChaoticLoki",
    "Age": 22,
    "Sex": "Male"
}

I was hoping I could return something like:

{
    "data": {
        "Name": "ChaoticLoki",
        "Age": 22,
        "Sex": "Male",
    },
    "success": true
}

Upvotes: 1

Views: 61

Answers (1)

zs2020
zs2020

Reputation: 54524

You can then create a class wrapping the data and status like this

public class JsonResult{
    public object data { get; set;}
    public boolean success { get; set;}
}

And then in your Web Api methods, you can do

var data = ... //getting from repo
return Json(new JsonResult{data = data, success = true});

Upvotes: 2

Related Questions