Using Json.NET you can achieve what you need. You can create a derived class of JsonResult that uses Json.NET instead of the default ASP.NET MVC JavascriptSerializer:
/// <summary>
/// Custom JSON result class using JSON.NET.
/// </summary>
public class JsonNetResult : JsonResult
{
/// <summary>
/// Initializes a new instance of the <see cref="JsonNetResult" /> class.
/// </summary>
public JsonNetResult()
{
Settings = new JsonSerializerSettings
{
ReferenceLoopHandling = ReferenceLoopHandling.Error
};
}
/// <summary>
/// Gets the settings for the serializer.
/// </summary>
public JsonSerializerSettings Settings { get; set; }
/// <summary>
/// Try to retrieve JSON from the context.
/// </summary>
/// <param name="context">Basic context of the controller doing the request</param>
public override void ExecuteResult(ControllerContext context)
{
if (context == null)
{
throw new ArgumentNullException("context");
}
if (JsonRequestBehavior == JsonRequestBehavior.DenyGet &&
string.Equals(context.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase))
{
throw new InvalidOperationException("JSON GET is not allowed");
}
HttpResponseBase response = context.HttpContext.Response;
response.ContentType = string.IsNullOrEmpty(ContentType) ? "application/json" : ContentType;
if (ContentEncoding != null)
{
response.ContentEncoding = ContentEncoding;
}
if (Data == null)
{
return;
}
var scriptSerializer = JsonSerializer.Create(Settings);
using (var sw = new StringWriter())
{
scriptSerializer.Serialize(sw, Data);
response.Write(sw.ToString());
}
}
}
Then, use this class in your Controller for return data:
public JsonResult Index()
{
var response = new ToastrMessage { ToasterType = ToasterType.success };
return new JsonNetResult { Data = response, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
In this way, you get your desired result:
{ ToasterType: "success" }
Please note that this solution is based on this post, so the credits are for the author :)