为什么 [Serializable] 导致 Newtonsoft.Json 序列化程序包含支持字段?
Why does [Serializable] cause Newtonsoft.Json serializer to include backing fields?
如果我在 class 上具有 [Serializable] 属性,那么它会导致生成的序列化 Json 字符串包含由框架创建的支持成员。
例如,我的 Id 字段如下所示:
<Id>k__BackingField=20001
我可以在 SOF 和其他地方找到许多资源来解决这个问题,但我找不到为什么 Json 序列化程序在看到 [Serializable] 属性时表现不同。
如果 Jason 序列化程序不序列化成员而只序列化属性,那么当 class 用 [Serializable] 属性装饰时,为什么它的行为会有所不同?
请注意,我并不是在寻找解决此问题的方法,因为我已经找到了。我想知道为什么 Newtonsoft.Jsonserialiser 在这里表现不同。
以防以后有人想找原因,下面解释对象是如何被Json.Net序列化的:
Breakdown of Type Serialization > Objects
By default a type's properties are serialized in opt-out mode. What
that means is that all public fields and properties with getters are
automatically serialized to JSON, and fields and properties that
shouldn't be serialized are opted-out by placing JsonIgnoreAttribute
on them. To serialize private members, the JsonPropertyAttribute can
be placed on private fields and properties.
Types can also be serialized using opt-in mode. Only properties and
fields that have a JsonPropertyAttribute or DataMemberAttribute on
them will be serialized. Opt-in mode for an object is specified by
placing the JsonObjectAttribute or DataContractAttribute on the type.
Finally, types can be serialized using a fields mode. All fields, both
public and private, are serialized and properties are ignored. This
can be specified by setting MemberSerialization.Fields on a type with
the JsonObjectAttribute or by using the .NET SerializableAttribute and
setting IgnoreSerializableAttribute on DefaultContractResolver to
false.
如果我在 class 上具有 [Serializable] 属性,那么它会导致生成的序列化 Json 字符串包含由框架创建的支持成员。
例如,我的 Id 字段如下所示:
<Id>k__BackingField=20001
我可以在 SOF 和其他地方找到许多资源来解决这个问题,但我找不到为什么 Json 序列化程序在看到 [Serializable] 属性时表现不同。
如果 Jason 序列化程序不序列化成员而只序列化属性,那么当 class 用 [Serializable] 属性装饰时,为什么它的行为会有所不同?
请注意,我并不是在寻找解决此问题的方法,因为我已经找到了。我想知道为什么 Newtonsoft.Jsonserialiser 在这里表现不同。
以防以后有人想找原因,下面解释对象是如何被Json.Net序列化的:
Breakdown of Type Serialization > Objects
By default a type's properties are serialized in opt-out mode. What that means is that all public fields and properties with getters are automatically serialized to JSON, and fields and properties that shouldn't be serialized are opted-out by placing JsonIgnoreAttribute on them. To serialize private members, the JsonPropertyAttribute can be placed on private fields and properties.
Types can also be serialized using opt-in mode. Only properties and fields that have a JsonPropertyAttribute or DataMemberAttribute on them will be serialized. Opt-in mode for an object is specified by placing the JsonObjectAttribute or DataContractAttribute on the type.
Finally, types can be serialized using a fields mode. All fields, both public and private, are serialized and properties are ignored. This can be specified by setting MemberSerialization.Fields on a type with the JsonObjectAttribute or by using the .NET SerializableAttribute and setting IgnoreSerializableAttribute on DefaultContractResolver to false.