-
Notifications
You must be signed in to change notification settings - Fork 5.3k
Add option to ignore reference cycles on serialization #46101
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
152db42
f980ad0
0eaf149
2e55d73
1905462
aafaf2f
b562579
216caae
75ef177
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,12 @@ | ||
| // Licensed to the .NET Foundation under one or more agreements. | ||
| // The .NET Foundation licenses this file to you under the MIT license. | ||
|
|
||
| namespace System.Text.Json.Serialization | ||
| { | ||
| internal sealed class IgnoreReferenceHandler : ReferenceHandler | ||
| { | ||
| public IgnoreReferenceHandler() => HandlingStrategy = ReferenceHandlingStrategy.IgnoreCycles; | ||
|
|
||
| public override ReferenceResolver CreateResolver() => new IgnoreReferenceResolver(); | ||
| } | ||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,42 @@ | ||
| // Licensed to the .NET Foundation under one or more agreements. | ||
| // The .NET Foundation licenses this file to you under the MIT license. | ||
|
|
||
| using System.Collections.Generic; | ||
| using System.Diagnostics; | ||
|
|
||
| namespace System.Text.Json.Serialization | ||
| { | ||
| internal sealed class IgnoreReferenceResolver : ReferenceResolver | ||
| { | ||
| // The stack of references on the branch of the current object graph, used to detect reference cycles. | ||
| private Stack<ReferenceEqualsWrapper>? _stackForCycleDetection; | ||
|
|
||
| internal override void PopReferenceForCycleDetection() | ||
| { | ||
| Debug.Assert(_stackForCycleDetection != null); | ||
| _stackForCycleDetection.Pop(); | ||
| } | ||
|
|
||
| internal override bool ContainsReferenceForCycleDetection(object value) | ||
| => _stackForCycleDetection?.Contains(new ReferenceEqualsWrapper(value)) ?? false; | ||
|
|
||
| internal override void PushReferenceForCycleDetection(object value) | ||
| { | ||
| var wrappedValue = new ReferenceEqualsWrapper(value); | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Why do we have this
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Therefore we use
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Opposed to this, we can avoid forcing reference equality and rely on object.Equals, which is what Newtonsoft does (see JamesNK/Newtonsoft.Json#401 (comment)). Also, Newtonsoft offers
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I prefer the current choice of forcing reference equality for this feature since it aligns with Preserve, which uses If requested by users, we can consider adding an API to a future extensibility model which allows users to specify an equality comparer to use with IgnoreCycles.
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Got it, thanks. This doesn't affect behavior when this feature is off (happy path), but are there any perf issues with struct copies when inserting/checking/extracting from the stack?
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. We only pass reference-types to the stack, in the case of boxed structs, there is no copy semantics applying given that we never unbox. |
||
|
|
||
| if (_stackForCycleDetection is null) | ||
| { | ||
| _stackForCycleDetection = new Stack<ReferenceEqualsWrapper>(); | ||
| } | ||
|
|
||
| Debug.Assert(!_stackForCycleDetection.Contains(wrappedValue)); | ||
| _stackForCycleDetection.Push(wrappedValue); | ||
| } | ||
|
|
||
| public override void AddReference(string referenceId, object value) => throw new InvalidOperationException(); | ||
|
|
||
| public override string GetReference(object value, out bool alreadyExists) => throw new InvalidOperationException(); | ||
|
|
||
| public override object ResolveReference(string referenceId) => throw new InvalidOperationException(); | ||
| } | ||
| } | ||
| Original file line number | Diff line number | Diff line change | ||||||
|---|---|---|---|---|---|---|---|---|
|
|
@@ -196,7 +196,8 @@ internal bool TryRead(ref Utf8JsonReader reader, Type typeToConvert, JsonSeriali | |||||||
| ref reader); | ||||||||
| } | ||||||||
|
|
||||||||
| if (CanBePolymorphic && options.ReferenceHandler != null && value is JsonElement element) | ||||||||
| if (options.ReferenceHandlingStrategy == ReferenceHandlingStrategy.Preserve && | ||||||||
| CanBePolymorphic && value is JsonElement element) | ||||||||
| { | ||||||||
| // Edge case where we want to lookup for a reference when parsing into typeof(object) | ||||||||
| // instead of return `value` as a JsonElement. | ||||||||
|
|
@@ -303,23 +304,48 @@ internal bool TryWrite(Utf8JsonWriter writer, in T value, JsonSerializerOptions | |||||||
| ThrowHelper.ThrowJsonException_SerializerCycleDetected(options.EffectiveMaxDepth); | ||||||||
| } | ||||||||
|
|
||||||||
| if (CanBeNull && !HandleNullOnWrite && IsNull(value)) | ||||||||
| { | ||||||||
| // We do not pass null values to converters unless HandleNullOnWrite is true. Null values for properties were | ||||||||
| // already handled in GetMemberAndWriteJson() so we don't need to check for IgnoreNullValues here. | ||||||||
| writer.WriteNullValue(); | ||||||||
| return true; | ||||||||
| } | ||||||||
|
|
||||||||
| bool ignoreCyclesPopReference = false; | ||||||||
| if (options.ReferenceHandlingStrategy == ReferenceHandlingStrategy.IgnoreCycles && | ||||||||
| !IsValueType && !IsNull(value)) | ||||||||
| { | ||||||||
| Debug.Assert(value != null); | ||||||||
| ReferenceResolver resolver = state.ReferenceResolver; | ||||||||
|
|
||||||||
| // Write null to break reference cycles. | ||||||||
| if (resolver.ContainsReferenceForCycleDetection(value)) | ||||||||
| { | ||||||||
| writer.WriteNullValue(); | ||||||||
| return true; | ||||||||
| } | ||||||||
|
|
||||||||
| // For boxed reference types: do not push when boxed in order to avoid false positives | ||||||||
| // when we run the ContainsReferenceForCycleDetection check for the converter of the unboxed value. | ||||||||
| if (!CanBePolymorphic) | ||||||||
| { | ||||||||
| resolver.PushReferenceForCycleDetection(value); | ||||||||
| ignoreCyclesPopReference = true; | ||||||||
| } | ||||||||
| } | ||||||||
|
|
||||||||
| if (CanBePolymorphic) | ||||||||
| { | ||||||||
| if (value == null) | ||||||||
| { | ||||||||
| if (!HandleNullOnWrite) | ||||||||
| { | ||||||||
| writer.WriteNullValue(); | ||||||||
| } | ||||||||
| else | ||||||||
| { | ||||||||
| Debug.Assert(ClassType == ClassType.Value); | ||||||||
| Debug.Assert(!state.IsContinuation); | ||||||||
| Debug.Assert(ClassType == ClassType.Value); | ||||||||
| Debug.Assert(!state.IsContinuation); | ||||||||
| Debug.Assert(HandleNullOnWrite); | ||||||||
layomia marked this conversation as resolved.
Show resolved
Hide resolved
|
||||||||
|
|
||||||||
| int originalPropertyDepth = writer.CurrentDepth; | ||||||||
| Write(writer, value, options); | ||||||||
| VerifyWrite(originalPropertyDepth, writer); | ||||||||
| } | ||||||||
| int originalPropertyDepth = writer.CurrentDepth; | ||||||||
| Write(writer, value, options); | ||||||||
| VerifyWrite(originalPropertyDepth, writer); | ||||||||
|
|
||||||||
| return true; | ||||||||
| } | ||||||||
|
|
@@ -339,18 +365,26 @@ internal bool TryWrite(Utf8JsonWriter writer, in T value, JsonSerializerOptions | |||||||
| JsonConverter jsonConverter = state.Current.InitializeReEntry(type, options); | ||||||||
| if (jsonConverter != this) | ||||||||
layomia marked this conversation as resolved.
Show resolved
Hide resolved
|
||||||||
| { | ||||||||
| if (options.ReferenceHandlingStrategy == ReferenceHandlingStrategy.IgnoreCycles && | ||||||||
| jsonConverter.IsValueType) | ||||||||
| { | ||||||||
| // For boxed value types: push the value before it gets unboxed on TryWriteAsObject. | ||||||||
| state.ReferenceResolver.PushReferenceForCycleDetection(value); | ||||||||
| ignoreCyclesPopReference = true; | ||||||||
| } | ||||||||
|
|
||||||||
| // We found a different converter; forward to that. | ||||||||
| return jsonConverter.TryWriteAsObject(writer, value, options, ref state); | ||||||||
| bool success2 = jsonConverter.TryWriteAsObject(writer, value, options, ref state); | ||||||||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. A variable named runtime/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonConverterOfT.cs Line 384 in 148bc08
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Consider making this one |
||||||||
|
|
||||||||
| if (ignoreCyclesPopReference) | ||||||||
| { | ||||||||
| state.ReferenceResolver.PopReferenceForCycleDetection(); | ||||||||
layomia marked this conversation as resolved.
Show resolved
Hide resolved
|
||||||||
| } | ||||||||
|
|
||||||||
| return success2; | ||||||||
| } | ||||||||
| } | ||||||||
| } | ||||||||
| else if (CanBeNull && !HandleNullOnWrite && IsNull(value)) | ||||||||
| { | ||||||||
| // We do not pass null values to converters unless HandleNullOnWrite is true. Null values for properties were | ||||||||
| // already handled in GetMemberAndWriteJson() so we don't need to check for IgnoreNullValues here. | ||||||||
| writer.WriteNullValue(); | ||||||||
| return true; | ||||||||
| } | ||||||||
|
|
||||||||
| if (ClassType == ClassType.Value) | ||||||||
| { | ||||||||
|
|
@@ -390,6 +424,11 @@ internal bool TryWrite(Utf8JsonWriter writer, in T value, JsonSerializerOptions | |||||||
|
|
||||||||
| state.Pop(success); | ||||||||
|
|
||||||||
| if (ignoreCyclesPopReference) | ||||||||
| { | ||||||||
| state.ReferenceResolver.PopReferenceForCycleDetection(); | ||||||||
| } | ||||||||
|
|
||||||||
| return success; | ||||||||
| } | ||||||||
|
|
||||||||
|
|
||||||||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,16 @@ | ||
| // Licensed to the .NET Foundation under one or more agreements. | ||
| // The .NET Foundation licenses this file to you under the MIT license. | ||
|
|
||
| using System.Runtime.CompilerServices; | ||
|
|
||
| namespace System.Text.Json.Serialization | ||
| { | ||
| internal struct ReferenceEqualsWrapper : IEquatable<ReferenceEqualsWrapper> | ||
| { | ||
| private object _object; | ||
| public ReferenceEqualsWrapper(object obj) => _object = obj; | ||
| public override bool Equals(object? obj) => obj is ReferenceEqualsWrapper otherObj && Equals(otherObj); | ||
| public bool Equals(ReferenceEqualsWrapper obj) => ReferenceEquals(_object, obj._object); | ||
| public override int GetHashCode() => RuntimeHelpers.GetHashCode(_object); | ||
| } | ||
| } |
Uh oh!
There was an error while loading. Please reload this page.