Can DataContractJsonSerializer handle cyclic references?

夙愿已清 提交于 2019-12-10 10:47:59

问题


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

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.

Will DataContractJsonSerializer also honor the IsReference property?


回答1:


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

When applying DataContractAttribute.IsReference = true on the class subject to serialization,

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

and trying to serialize it using the DataContractJsonSerializer,

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

The WriteObject method will throw an exception:

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.

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

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



来源:https://stackoverflow.com/questions/19975600/can-datacontractjsonserializer-handle-cyclic-references

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!