Skip to content

Provide trim/AOT-safe mechanism to (de)serialize enums from strings with JSON source-gen #79311

@layomia

Description

@layomia

See #79311 (comment) for an updated API proposal.

Original Proposal

Background and Motivation

The JsonStringEnumConverter class is a built-in JsonConverterFactory that is not compatible with NativeAOT, since it relies on Type.MakeGenericType() to work. We need to update the source generator so that it intercepts [JsonConverter(typeof(JsonStringEnumConverter))] annotations and replaces them with a NativeAOT-safe factory method invocation.

Should be addressed in conjunction with #81833.

API Proposal

namespace System.Text.Json.Serialization.Metadata;

public static class JsonMetadataServices
{
    public static JsonConverter<T> GetEnumConverter<T>(JsonSerializerOptions options) where T : struct, Enum
+   public static JsonConverter<T> GetStringEnumConverter<T>(JsonStringEnumConverter converterFactory, JsonSerializerOptions options) where T : struct, Enum
}

Alternative Design

We could add the generic factory method on the converter factory itself:

public class JsonStringEnumConverter
{
    public JsonConverter CreateConverter(Type typeToConvert, JsonSerializerOptions options);
+   public JsonConverter<T> CreateConverter<T>(JsonSerializerOptions options) where T : struct, Enum
}

However I would prefer if this call were hidden behind the EditorBrowsable.Never JsonMetadataServices class.

Edited by @eiriktsarpalis

Original Proposal Forking from https://github.com//issues/73124 which goes over a friendly, general pattern for JsonConverterFactory usage with source-gen.

This issue focuses on a plan to support [JsonStringEnumConverter] (or an alternate approach), the primary scenario needed in 8.0 for the ASP.NET effort for AOT friendlinessfriendliness (JSON items tracked by #79122).

Metadata

Metadata

Labels

api-approvedAPI was approved in API review, it can be implementedarea-System.Text.JsonblockingMarks issues that we want to fast track in order to unblock other important workblocking-releasepartner-impactThis issue impacts a partner who needs to be kept updatedsource-generatorIndicates an issue with a source generator featuretrimming-for-aot`EnableAggressiveTrimming=true` used for running tests with AOT

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions