2

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

3 Answers 3

5

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

4 Comments

I use Json method, of course. But I dont get this structure.
@bluray What structure do you get?
I need this structure { "title": "T1", "data": [ { "value": "v1", "key": "k1" }, { "value": "v2", "key": "k2" } ] }
@bluray I get the structure that you need with code which I provided (here the output of my browser prnt.sc/auwzxd). What version of ASP.NET MVC do you use?
2

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);

Comments

0

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))

Comments

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.