Return data as JSON using ASP.NET MVC

Asked

Viewed 633 times

6

When developing a web application, using ASP.NET MVC, I need to return the layer of view, data as JSON in the following format:

{
    'title': 'Gallery 1',
    'description': 'Description of gallery...',
    'thumbnail': 
        [
            '1.jpg', 
            '2.jpg', 
            '3.jpg', 
            '4.jpg', 
            '11.jpg'
        ],
    'large': 
        [
            'large/1.jpg', 
            'large/2.jpg', 
            'large/3.jpg', 
            'large/4.jpg', 
            'large/11.jpg'
        ],
    'button_list':
        [
            { 
                'title': 'Demo', 
                'url': 'http://demo.com' 
            },
            { 
                'title': 'Download', 
                'url': 'http://download.com' 
            }
        ],
    'tags': ['All','Photoshop']
}

What is the best way for me to assemble this JSON, or a list of it, in my controller to return him to the view?

1 answer

4


To have more freedom in the customization of JSON that will be returned I recommend that you use a library called Json.NET (Package link in Nuget).

After installing Json.NET in the project set one model which will be "serialized" to JSON by the library and use the attribute JsonProperty to define a custom name for each JSON property that will be returned.

I rode two models based on the example JSON in your question:

public class Thing
{
    [JsonProperty(PropertyName = "title")]
    public string Title { get; set; }

    [JsonProperty(PropertyName = "description")]
    public string Description { get; set; }

    [JsonProperty(PropertyName = "thumbnail")]
    public string[] Thumbnail { get; set; }

    [JsonProperty(PropertyName = "large")]
    public string[] Large { get; set; }

    [JsonProperty(PropertyName = "button_list")]
    public ThingButton[] ButtonList { get; set; }

    [JsonProperty(PropertyName = "tags")]
    public string[] Tags { get; set; }
}

public class ThingButton
{
    [JsonProperty(PropertyName = "title")]
    public string Title { get; set; }

    [JsonProperty(PropertyName = "url")]
    public string Url { get; set; }
}

It will also be necessary to extend JsonResult to support the Json.NET library, to do this I used a class created by a Soen user in that answer here, it is well made and can be added to your project without any problem:

public class JsonNetResult : JsonResult
{
    public override void ExecuteResult(ControllerContext context)
    {
        if (context == null)
            throw new ArgumentNullException("context");

        var response = context.HttpContext.Response;

        response.ContentType = !String.IsNullOrEmpty(ContentType)
            ? ContentType
            : "application/json";

        if (ContentEncoding != null)
            response.ContentEncoding = ContentEncoding;

        // If you need special handling, you can call another form of SerializeObject below
        var serializedObject = JsonConvert.SerializeObject(Data, Formatting.Indented);
        response.Write(serializedObject);
    }
}

And then I rode a action method to illustrate the use:

public class HomeController : Controller
{
    public JsonNetResult GetThing()
    {
        var thing = new Thing
        {
            Title = "Gallery 1",
            Description = "Description of gallery...",
            Thumbnail = new string[]
            {
                "1.jpg",
                "2.jpg",
                "3.jpg",
                "4.jpg",
                "11.jpg"
            },
            Large = new string[]
            {
                "large/1.jpg",
                "large/2.jpg",
                "large/3.jpg",
                "large/4.jpg",
                "large/11.jpg"
            },
            ButtonList = new ThingButton[]
            {
                new ThingButton { Title = "Demo", Url = "http://demo.com" },
                new ThingButton { Title = "Download", Url = "http://download.com" }
            },
            Tags = new string[]
            {
                "All",
                "Photoshop"
            }
        };

        return new JsonNetResult { Data = thing, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
    }
}

And this is the return of a GET request to endpoint /Home/GetThing:

{
  "title": "Gallery 1",
  "description": "Description of gallery...",
  "thumbnail": [
    "1.jpg",
    "2.jpg",
    "3.jpg",
    "4.jpg",
    "11.jpg"
  ],
  "large": [
    "large/1.jpg",
    "large/2.jpg",
    "large/3.jpg",
    "large/4.jpg",
    "large/11.jpg"
  ],
  "button_list": [
    {
      "title": "Demo",
      "url": "http://demo.com"
    },
    {
      "title": "Download",
      "url": "http://download.com"
    }
  ],
  "tags": [
    "All",
    "Photoshop"
  ]
}
  • Beauty, and in case I need a list, in the example you created just return a list<Thing>, correct?

  • 1

    @Ericosouza Yes, just pass to the property Data of JsonNetResult one List<Thing> that Json.NET will take care of "serialization".

Browser other questions tagged

You are not signed in. Login or sign up in order to post.