可以DataContractJsonSerializer处理循环引用?DataContractJsonSerializer

2023-09-04 03:44:02 作者:很久没笑了

是否有任何的序列化/反序列化场景 DataContractSerializer的的可以的处理,而 DataContractJsonSerializer 的不能的?

Are there any serialization/deserialization scenarios that DataContractSerializer can handle, while DataContractJsonSerializer can't?

在特别的,我想到的是循环引用:这个MSDN网页解释如何循环引用可以通过的DataContractSerializer 通过使用管理 IsReference = TRUE DataContractAttribute 的构造。另一方面,在 DataContractAttribute.IsReference 文档没有明确指出其适用范围仅限于的DataContractSerializer

In particular, I am thinking of circular references: this MSDN page explains how circular references can be managed by DataContractSerializer via the use of IsReference = true in the DataContractAttribute constructor. On the other hand, the DataContractAttribute.IsReference documentation does not explicitly state that its applicability is limited to DataContractSerializer.

威尔 DataContractJsonSerializer 也兑现了 IsReference 属性?

推荐答案

有没有像一个好老的实际测试在下午...

There's nothing like a good old hands-on testing in the afternoon...

当应用 DataContractAttribute.IsReference = TRUE 的类受系列化,

[DataContract(IsReference = true)]
public class SerializableClass {
...
}

和尝试使用序列化到 DataContractJsonSerializer

var serializer = new DataContractJsonSerializer(typeof(SerializableClass));
serializer.WriteObject(stream, obj);

的writeObject 方法会抛出异常:

System.Runtime.Serialization.SerializationException:类型SerializableClass'不能被序列化到JSON,因为它的IsReference设置为真。 JSON格式不支持引用,因为没有再presenting没有引用任何标准格式。要启用系列化,禁用IsReference的类型或适当的父类的类型设置。

System.Runtime.Serialization.SerializationException : The type 'SerializableClass' cannot be serialized to JSON because its IsReference setting is 'True'. The JSON format does not support references because there is no standardized format for representing references. To enable serialization, disable the IsReference setting on the type or an appropriate parent class of the type.

如果我在另一方面利用的DataContractSerializer 连载同一个对象,序列化(和反序列化)的工作原理就像一个魅力。

If I on the other hand use DataContractSerializer to serialize the same object, serialization (and deserialization) works like a charm.

现在,如果有人与的DataContractSerializer 比较知道的 DataContractJsonSerializer 的更多的限制,我所有的耳朵...

Now, if anyone knows of more limitations of DataContractJsonSerializer in comparison with DataContractSerializer, I am all ears...