【问题标题】:Outputting Json with the Razor view engine使用 Razor 视图引擎输出 Json
【发布时间】:2010-12-06 13:55:08
【问题描述】:

我有一个dictionary<string,string> 作为我的视图模型的一部分。我想要做的是循环这个对象并将它作为一个 json 对象输出。我这样做的原因是我可以正确本地化我的客户端脚本文件。

这个输出需要看起来像

var clientStrings = {"test":"yay","goodBye":"Nah"};

关于如何正确实现这一点的任何想法。

提前致谢。

【问题讨论】:

    标签: asp.net-mvc json asp.net-mvc-3 razor


    【解决方案1】:

    它内置于 MVC 中。只需返回 Json(yourobject)。

    【讨论】:

      【解决方案2】:

      考虑到您使用的是 mvc 3,您将可以访问 JavaScriptSerializer。您应该能够执行以下操作:

      JavaScriptSerializer serializer = new JavaScriptSerializer();
      string json = serializer.Serialize((object)yourDictionary);
      

      这会将您的字典序列化为 json。在将 ViewData 发送到视图进行渲染之前,您可能希望在控制器中执行此操作。

      【讨论】:

        【解决方案3】:

        您还可以在您的代码中集成免费的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();
                }
            }
        }
        

        【讨论】:

        • 我不确定 JSON.NET 是否能够做字典,你能否确认它可以,因为这就是 RubbleFord 的要求
        • 无缝运行 :) 为了您的快乐,我编辑了我的答案
        • @Lorenzo,为什么在内置的 Json(xxx) 上使用它?有什么优势吗?
        • @Adam Tuliper:我无法确定,但我认为在内部 Json(xxx) 使用 JavaScriptSerializer 存在循环引用问题,您可以阅读它 here 和 @987654323 @。我的答案只是对已接受答案的补充,100% 正确
        • @AdamTuliper:JSON.NET 可以通过 JsonProperty 属性将您想要输出的属性列入白名单,请参阅stackoverflow.com/questions/2546138/…。此外,JSON.NET 可以序列化具有 getter 但没有 setter 的属性,而 WCF DataContract JSON 序列化程序不能。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-03-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-06-29
        • 1970-01-01
        • 2017-10-15
        相关资源
        最近更新 更多