JsonIgnore在System.Web.Mvc.Controller中不起作用 [英] JsonIgnore not working in System.Web.Mvc.Controller
问题描述
我有一个Web-API项目和一个带有一些属性的简单类,其中一些标记为<JsonIgnore>
.
I have a web-API project and a simple class with a few properties, some are marked <JsonIgnore>
.
在我的MVC控制器中,放入Return Json(instanceOfMyClass, JsonRequestBehavior.AllowGet)
.所有成员都已序列化.
我在我的WEBAPI控制器中放入了Return Json(Of MyClass)(instanceOfMyClass)
.仅存在我要序列化的成员.
In my MVC-controller I put Return Json(instanceOfMyClass, JsonRequestBehavior.AllowGet)
. All members are serialized.
I put Return Json(Of MyClass)(instanceOfMyClass)
in my WEBAPI-controller. Only the members I intend to serialize are present.
如何独立于将要序列化的控制器而忽略这些属性.
How can I ignore these properties independent of the controller that's going to serialize.
推荐答案
MVC中的JsonResult
实际上并未使用JSON.NET,这就是[JsonIgnore]
无法正常工作的原因.而是使用JavaScriptSerializer
类.
The JsonResult
in MVC does not actually use JSON.NET which is why [JsonIgnore]
is not working. Instead it uses the JavaScriptSerializer
class.
要使JavaScriptSerializer
跳过属性,可以在模型属性上使用[ScriptIgnore]
属性.
To make the JavaScriptSerializer
skip a property, you can you the [ScriptIgnore]
attribute on your model property.
另一种选择是使用JSON.NET的JsonConvert
创建自定义ActionResult
来序列化对象,然后使用[JsonIgnore]
属性.
An alternative would be to make a custom ActionResult
that uses JSON.NET's JsonConvert
to serialize the object which would then honor the [JsonIgnore]
attribute.
这篇关于JsonIgnore在System.Web.Mvc.Controller中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!