Circular reference in JsonSerializer

34 Views Asked by At

I have a list of objects with links to each other to get a double linked chain. Although I marked the links not to be considered in the serializer I get the message

"A possible object cycle was detected. This can either be due to a cycle or if the object depth is larger than the maximum allowed depth of 64. Consider using ReferenceHandler.Preserve on JsonSerializerOptions to support cycles. Path: $.pSuccessor.pSuccessor.pSuccessor.pSuccessor.pSuccessor.pSuccessor.pPredecessor.pSuccessor.pPredecessor. ... .pPredecessor.Location.IsEmpty."

The objects are defined in this way:

  public class BObject : Panel, ISerializable, ICloneable
  {
    public eObjectType typObject;
    ...
    [ScriptIgnore]
    public virtual BObject pSuccessor
    {
      get { return null; }
      set { }
    }

    [ScriptIgnore]
    public virtual BObject pPredecessor
    {
      get { return null; }
      set { }
    }
    ...
  }

  [Serializable]
  public partial class DvObject : BObject, ISerializable
  {
    [NonSerialized]
    [ScriptIgnore]
    protected DvObject pPrevious;
    [NonSerialized]
    [ScriptIgnore]
    protected DvObject pNext;
    ...
    [ScriptIgnore]
    public override BObject pSuccessor
    {
      get { return pNext; }
      set { pNext = (RvmComponent)value; }
    }

    public override BObject pPredecessor
    {
      get { return pPrevious; }
      set
      {
        ...
        pPrevious = (DvObject)value;
        ...
      }
    }
  }

The code processing the serialization where the error occurs is:

  foreach (BObject obj in lobj)
  {
    String jsonObj = JsonSerializer.Serialize(lobj, options);
  }

How is it possible to reach that the JsonSerializer ignors the other linked objects and doesn't try to serialize them?

1

There are 1 best solutions below

0
Thomas Koelle On BEST ANSWER

I think you are just looking for:

[JsonIgnore]