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

前端 未结 5 828
我寻月下人不归
我寻月下人不归 2021-02-13 00:04

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\".<

5条回答
  •  你的背包
    2021-02-13 01:06

    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. The DataContract attribute tells the various serializers to ignore any property that doesn't have the DataMember attribute.

    There are two major benefits compared to using ScriptIgnoreAttribute. First, it doesn't have a dependency on the System.Web.Extensions assembly. Second, it works with other types of serialization, not just 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.

    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.

提交回复
热议问题