简体   繁体   English

如何在ASP.NET MVC中阻止JSON序列化?

[英]How do I prevent JSON serialization in ASP.NET MVC?

While developing an ASP.NET MVC app, I'm finding a few places where my JsonResult actions throw an exception "A circular reference was detected while serializing an object". 在开发ASP.NET MVC应用程序时,我发现了一些我的JsonResult操作引发异常的地方“序列化对象时检测到循环引用”。

For now, I'm removing the references in question, but ideally I'd like to simply mark the property such that the JSON serializer ignores it. 现在,我正在删除有问题的引用,但理想情况下我只想标记属性,使JSON序列化程序忽略它。

Can anyone suggest how I might do this? 谁能建议我怎么做?

[ScriptIgnore] 应该适合你。

I've generally found that for complex objects its best to just serialize by creating a temporary 'inbetween' object : 我一般发现,对于复杂的对象,最好通过创建一个临时的“inbetween”对象进行序列化:

For instance for testimonials I do the following. 例如,对于推荐,我会做以下事情。 I actually do this in the codebehind for my ASPX model page. 我实际上在我的ASPX模型页面的代码隐藏中这样做。

This creates a nice JSON object. 这会创建一个漂亮的JSON对象。 You'll notice I can even refactor my model and the page will still work. 您会注意到我甚至可以重构我的模型,页面仍然有效。 Its just another layer of abstraction between the data model and the page. 它只是数据模型和页面之间的另一层抽象。 I dont think my controller should know about JSON as much as possible, but the ASPX 'codebehind' certainly can. 我不认为我的控制器应尽可能多地了解JSON,但ASPX'代码隐藏'当然可以。

/// <summary>
/// Get JSON for testimonials
/// </summary>
public string TestimonialsJSON
{
    get
    {
        return Model.Testimonials.Select(
            x => new
            {
                testimonial = x.TestimonialText,
                name = x.name
            }
            ).ToJSON();
    }
}

In my ASPX I just do this in a block: 在我的ASPX中,我只是在一个块中执行此操作:

var testimonials = <%= TestimonialsJSON %>;

// oh and ToJSON() is an extension method
public static class ObjectExtensions
{
    public static string ToJSON(this Object obj)
    {
        return new JavaScriptSerializer().Serialize(obj);
    }
}

I'm ready for the backlash against this suggestion... bring it on... 我已经准备好反对这个建议了......把它带上......

I'm not accessing data, merely reformatting a model for the View. 我没有访问数据,只是重新格式化View的模型。 This is 'view model' logic, not 'controller model' logic. 这是'视图模型'逻辑,而不是'控制器模型'逻辑。

I would advise to use JSON.NET . 我建议使用JSON.NET It allows to serialize circular references and provides much more serialization options. 它允许序列化循环引用并提供更多的序列化选项。

What Simon said. 西蒙说的话。 Add a little AutoMapper action to keep code weight under control. 添加一些AutoMapper操作以控制代码权重。

The cleanest approach i've found is to use a combination of [DataContract] on the class and [DataMember] on the properties you want to serialize. 我发现最干净的方法是在类上使用[DataContract]和在要序列化的属性上使用[DataMember]。 The DataContract attribute tells the various serializers to ignore any property that doesn't have the DataMember attribute. DataContract属性告诉各种序列化程序忽略任何没有DataMember属性的属性。

There are two major benefits compared to using ScriptIgnoreAttribute. 与使用ScriptIgnoreAttribute相比,有两个主要的好处。 First, it doesn't have a dependency on the System.Web.Extensions assembly. 首先,它不依赖于System.Web.Extensions程序集。 Second, it works with other types of serialization, not just JSON. 其次,它适用于其他类型的序列化,而不仅仅是JSON。 For example, if you're using the new Web API in MVC 4, the DataContract/DataMember approach will work with the XML serializer as well. 例如,如果您在MVC 4中使用新的Web API,则DataContract / DataMember方法也将与XML序列化程序一起使用。

Consider the scenario where your entities are stored in an shared library and reused across various projects - you don't want a dependency on System.Web.Extensions, and you want to loosely describe serialization rules - not hardcode behavior specific to JSON, XML, etc. 考虑这样一种情况:您的实体存储在共享库中并在各种项目中重用 - 您不希望依赖于System.Web.Extensions,并且您希望松散地描述序列化规则 - 而不是特定于JSON,XML的硬编码行为,等等

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 ASP.NET MVC中的Json序列化错误 - Json Serialization Error in asp.net mvc asp.net中的json序列化mvc c# - Json serialization in asp.net mvc c# ASP.NET MVC Json DateTime序列化转换为UTC - ASP.NET MVC Json DateTime Serialization conversion to UTC ASP.NET MVC 4中的JSON日期序列化问题 - JSON date serialization issue in ASP.NET MVC 4 在ASP.Net MVC中使用Web Api Controller 2进行Json序列化 - Json Serialization using Web Api Controller 2 in ASP.Net MVC 如何防止ajaxSubmit中的“ return false;”与ASP.NET MVC RedirectToAction冲突 - How do I prevent “return false;” in ajaxSubmit from conflicting with ASP.NET MVC RedirectToAction 如何防止ASP.NET MVC在视图中缓存无效数据? - How do I prevent ASP.NET MVC from caching invalid data in my View? 在asp.net mvc中使用fileupload时,如何防止IE保存文件对话框 - How do I prevent IE save file dialog when using fileupload in asp.net mvc 如何在不使用JavaScript的情况下防止在ASP.NET MVC中双击? - How do I prevent double-clicking in ASP.NET MVC without using JavaScript? 如何从asp.net mvc2 json结果返回未命名的JSON字符串数组? - How do I return unnamed JSON string array from asp.net mvc2 json result?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM