【发布时间】:2012-04-27 12:26:53
【问题描述】:
我有一个我序列化的 DTO 类
Json.Serialize(MyClass)
如何排除它的 public 属性?
(它必须是公开的,因为我在其他地方的代码中使用它)
【问题讨论】:
-
你使用哪个序列化框架?
-
IgnoreDataMemberScriptIgnoreJsonIgnore取决于您使用的序列化程序 -
另外值得注意的是[NonSerialized]属性,该属性只适用于字段(不是属性),其他方面与JsonIgnore作用相同。
-
Trynko 的评论很有用....如果在某个字段上使用 IgnoreDataMember 不会出错,但不会应用。
-
注意你的命名空间。 [JsonIgnore] 属性存在于 Newtonsoft.Json 和 System.Text.Json.Serialization 命名空间中。在模型上使用 Newtonsoft.Json.JsonIgnore 很容易,然后使用 System.Text.Json.Serialization.JsonSerializer.Serialize 来序列化您的模型(反之亦然)。然后 JsonIgnore 属性被忽略。 :)