I\'ve got a dictionary
as part of my view model. What I\'m trying to do is cycle this object and output it as a json object. My reason for
Also you can integrate the free Json.NET library within your code.
This library does not suffer the problems JavascriptSerializer
has like the circular reference problem.
This is a sample using the library to output JSON from a controller action
public virtual ActionResult ListData() {
Dictionary<string, string> openWith = new Dictionary<string, string>();
openWith.Add( "txt", "notepad.exe" );
openWith.Add( "bmp", "paint.exe" );
openWith.Add( "dib", "paint.exe" );
openWith.Add( "rtf", "wordpad.exe" );
JsonNetResult jsonNetResult = new JsonNetResult();
jsonNetResult.Formatting = Formatting.Indented;
jsonNetResult.Data = openWith;
return jsonNetResult;
}
If you execute this action you will get the following results
{
"txt": "notepad.exe",
"bmp": "paint.exe",
"dib": "paint.exe",
"rtf": "wordpad.exe"
}
JsonNetResult is a simple custom wrapper class around the functionalities of the Json.NET library.
public class JsonNetResult : ActionResult
{
public Encoding ContentEncoding { get; set; }
public string ContentType { get; set; }
public object Data { get; set; }
public JsonSerializerSettings SerializerSettings { get; set; }
public Formatting Formatting { get; set; }
public JsonNetResult() {
SerializerSettings = new JsonSerializerSettings();
}
public override void ExecuteResult( ControllerContext context ) {
if ( context == null )
throw new ArgumentNullException( "context" );
HttpResponseBase response = context.HttpContext.Response;
response.ContentType = !string.IsNullOrEmpty( ContentType )
? ContentType
: "application/json";
if ( ContentEncoding != null )
response.ContentEncoding = ContentEncoding;
if ( Data != null ) {
JsonTextWriter writer = new JsonTextWriter( response.Output ) { Formatting = Formatting };
JsonSerializer serializer = JsonSerializer.Create( SerializerSettings );
serializer.Serialize( writer, Data );
writer.Flush();
}
}
}
It's built into MVC. Just return Json(yourobject).
Considering you are on mvc 3 you'll have access to JavaScriptSerializer. You should be able to do the following:
JavaScriptSerializer serializer = new JavaScriptSerializer();
string json = serializer.Serialize((object)yourDictionary);
This will serialize your dictionary to json. You may want to do this in the controller before sending the ViewData to the view to render.