您还可以在您的代码中集成免费的Json.NET 库。
这个库没有JavascriptSerializer 的循环引用问题。
这是一个使用库从控制器操作输出 JSON 的示例
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;
}
如果你执行这个动作你会得到以下结果
{
"txt": "notepad.exe",
"bmp": "paint.exe",
"dib": "paint.exe",
"rtf": "wordpad.exe"
}
JsonNetResult 是一个围绕 Json.NET 库功能的简单自定义包装类。
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();
}
}
}