Wednesday, November 23, 2011

Serializing a C# Enum to JSON by its name value

Lets assume I have an Account class that has a Status property. The Status property is of the type EAccountStatus. An action method in one of my ASP.NET MVC controllers must return an Account instance to the browser, in response to a jQuery Ajax call.

Here is the code for the class and enum:
The result of the action method is of the type System.Web.Mvc.JsonResult. Normally my controller action will look as follows:
public JsonResult GetAccount(int id)  
{  
    Account account = new Account() {  
        Id = 1,
        UserName = "joe",
        Status = EAccountStatus.Open
    };  
    return Json(account);  
}

Now I would like the corresponding JSON result in JavaScript to be:
{ "Id": "1", "UserName": "joe", "Status": "Open" }

Instead I get:
{ "Id": "1", "UserName": "joe", "Status": "1" }

That is, the EAccountStatus Enum property is serialized to an integer rather than a string containing its name. Is it possible to have the Enum serialized by its name value?

It turns out that the JSON.NET library contains an attribute class that does what I want. However, including that library in my application seems overkill for solving my (I still hope) small issue.

Following a post on stackoverflow.com I decided to write my own JavaScriptConverter class (see the download link at the end of this post). The class overrides the Serialize method to convert Enum objects in the desired way. Our Account object in JSON now looks like:
{ "Id": "1", "UserName": "joe", "Status": { "Name": "Open", "Value": "1" } }

The custom JavaScriptConverter class serializes Enum objects to JavaScript objects that contain both the Enum name and its value. The "Name": "Open" in this case is what we were after.

Unfortunately it is not straightforward to let a controller action use the custom converter. The following web.config setting is ignored by the default JsonResult implementation (this is probably a bug):

  
    
      
        
          
        
      
    
      

A custom JsonResult class that reads the JSON converter setting from the web.config file can be found here and in the source code download.

No comments:

Post a Comment