bluray
bluray

Reputation: 1963

ASP MVC - create json structure

i have a problem. I would like create this json structure in ASP Controller:

{
"title": "T1",
"data": [
    { "value": "v1", "key": "k1" },
    { "value": "v2",       "key": "k2" }
]
}   

I tried this:

var data = new
        {
            title = "T1",
            data = new[]
            {
                new
                {
                    value = "V1",
                    key= "K1"
                },
                new
                {
                    value = "V2",
                    key= "K2"
                }
            }
        };

Thanks for advice

Upvotes: 2

Views: 4069

Answers (3)

Hypnobrew
Hypnobrew

Reputation: 1140

You can use the excellent Json.Net like:

JObject jsonObject = JObject.FromObject(data);
var json = jsonObject.ToString();

Where data is your anonymous object you posted above.
Json.Net can be downloaded via Nuget as Install-Package Newtonsoft.Json

(If it's a controller action you can just return Json(data))

Upvotes: 0

Tanya Petkova
Tanya Petkova

Reputation: 155

You can use either JsonConvert.SerializeObject() method from Newtonsoft.Json package to convert your data object to string in json format:

var json = JsonConvert.SerializeObject(data);

Upvotes: 2

chameleon
chameleon

Reputation: 1004

You can use Json method in your controller's action:

    [HttpGet]
    public ActionResult GetJsonData()
    {
        var data = new
        {
            title = "T1",
            data = new[]
            {
                new
                {
                    value = "V1",
                    key = "K1"
                },
                new
                {
                    value = "V2",
                    key = "K2"
                }
            }
        };
        return Json(data, JsonRequestBehavior.AllowGet);
    }

Upvotes: 5

Related Questions