Tuesday, July 06, 2010

Serializing anonymous classes

I ran into a situation where I found a need for a compound class that contained bits and pieces from quite a few other classes. The class would only be used for pushing data to the front end as a JSON formatted response in this rather special scenario. Rather than defining a new model/class I found that you can use an anonymous class and serialize it.

A brief note on the missing [DataContract]/[DataMember] and [Serializable] attributes, they are not needed for serializing public fields or properties in .NET 3.5 SP1.


Here are the predefined contrived classes
namespace MvcApplication1.Models
{
    public class Contact
    {
        public string Name { get; set; }
        public string PreferedEmail { get; set; }
    }
}

namespace MvcApplication1.Models
{
    public class ContactDetails
    {
        public string[] Emails { get; set; }
    }
}


controller
using System.Web.Mvc;
using MvcApplication1.Models;
using System.Web.Script.Serialization;

namespace MvcApplication1.Controllers
{
    public class HomeController : Controller
    {
        /// 
        /// Shows serializing a new anonymous class that contains some preexisting classes
        /// And serializing this using the JavaScriptSerializer
        /// 
        /// 
        public ActionResult SerializeAnonymousClassToJson()
        {
            var compositeContacts = new
            {
                MyContact = new Contact()
                {
                    Name = "Donald Duck",
                    PreferedEmail = "donaldduck@disney.com"
                },
                MyContactDetails = new ContactDetails()
                {
                    Emails = new[] 
                    { 
                        "donald@disney.com", 
                        "unclescroogenephew@scrooge.com" 
                    }
                }
            };
            JavaScriptSerializer jss = new JavaScriptSerializer();
            ViewData["Json"] = jss.Serialize(compositeContacts);
            return View();
        }
    }
}

and view.
<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<dynamic>" %>
<%= ViewData["Json"]%> 

and the serialized data looks like this

{"MyContact":{"Name":"Donald Duck","PreferedEmail":"donaldduck@disney.com"},"MyContactDetails":{"Emails":["donald@disney.com","unclescroogenephew@scrooge.com"]}}
Post a Comment