Return data as JSON using ASP.NET MVC

6

When developing a web application, using ASP.NET MVC, I need to return the view layer, 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's the best way for me to mount this JSON, or a list of it, in my controller to return it to view ?     
asked by anonymous 25.12.2015 / 14:52

1 answer

4

To get more freedom in customizing the JSON that will be returned I recommend that you use a library called Json.NET (< a href="https://www.nuget.org/packages/Newtonsoft.Json/"> Nuget package link ).

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

I've set up 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 this 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 put a action method to illustrate the usage:

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 the 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"
  ]
}
    
25.12.2015 / 15:46