dotnet / runtime

.NET is a cross-platform runtime for cloud, mobile, desktop, and IoT apps.
https://docs.microsoft.com/dotnet/core/
MIT License
15.41k stars 4.76k forks source link

[API Proposal]: System.Json reference handling allow per-type customization #110048

Open cpiber opened 16 hours ago

cpiber commented 16 hours ago

Background and motivation

ReferenceHandler.Preserve is very useful when references to the same object need to be sent. However, it easily breaks, for example with Tuple<>, since it does not have a constructor of the expected form.

It would be useful, if the user could opt-in to reference preservation only for specific types. I read a little through the implementation, and it seems like JsonConverter.CanHaveMetadata could already do what I need, but it is marked as internal and thus cannot be influenced by the user.

API Proposal

-

API Usage

class MyReferenceConverter : ObjectConverterFactory {
  public override JsonConverter CreateConverter(Type typeToConvert, JsonSerializerOptions options) {
    var converter = base.CreateConverter(typeToConvert, options);
    converter.CanHaveMetadata = typeToConvert != typeof(Tuple<>);
    return converter;
  }
}

Alternative Designs

No response

Risks

The property setter should probably only allow setting to false, as reference preserving on value types is not supported, and the converter must already support writing metadata, as implemented by ObjectDefaultConverter.

dotnet-policy-service[bot] commented 16 hours ago

Tagging subscribers to this area: @dotnet/area-system-text-json, @gregsdennis See info in area-owners.md if you want to be subscribed.