StackOverflowException is thrown when serialising circular dependent ISerializable object with ReferenceLoopHandling.Ignore

后端 未结 2 753
日久生厌
日久生厌 2020-12-18 02:06

I have a legacy application that used binary serialisation to persist the data. Now we wanted to use Json.net 4.5 to serialise the data without much changes to the existing

相关标签:
2条回答
  • 2020-12-18 02:26

    I think you'll need both ReferenceLoopHandling.Serialize and PreserveReferencesHandling.All to replicate the behavior of binary serialization. The resulting JSON may not be nearly as pretty, though.

    EDIT: I've looked deeper into JSON.Net 4.5r10 and discovered a deficiency: JsonSerializerInternalWriter doesn't check #ShouldWriteReference for references obtained via ISerializable.

    With the foreach loop in #SerializeISerializable rewritten as below, your object graph round-trips successfully.

      foreach (SerializationEntry serializationEntry in serializationInfo)
      {
        writer.WritePropertyName(serializationEntry.Name);
        var entryValue = serializationEntry.Value;
        var valueContract = GetContractSafe(entryValue);
        if (ShouldWriteReference(entryValue, null, valueContract, null, member))
        {
          WriteReference(writer, entryValue);
        }
        else
        {
          SerializeValue(writer, entryValue, valueContract, null, null, member);
        }
      }
    
    0 讨论(0)
  • 2020-12-18 02:26

    Did you try this?

    [Serializable]
     class Employee : ISerializable
     {
       [NonSerialized]
       [XmlIgnore]
       public Department Department { get; set; }
    

    NonSerialized Indicates that a field of a serializable class should not be serialized.

    XmlIgnore Instructs the Serialize method of the XmlSerializer not to serialize the public field or public read/write property value

    0 讨论(0)
提交回复
热议问题