Skip to content

OpenApiSchema System.Text.Json (De)Serialization #2299

Description

@Poltuu

Is your feature request related to a problem? Please describe.
Default System.Text.Json Serialization of OpenApiJsonSchema is verbose (complete) and unsatisfying.

Describe the solution you'd like
A simple way to fix it, probably via a JsonConverter, either by default or to configure on AddMVC json options.

Describe alternatives you've considered

Otherwise, OpenApiSchema could support direct serialization to a JsonWriter:

Additional context
Turns out I did it in my projects, and I also just really wanted to know if this was appropriate, or I missed something available

internal class SchemaConverter : System.Text.Json.Serialization.JsonConverter<OpenApiSchema>
{
	private static readonly ConcurrentDictionary<int, JsonSerializerOptions> _jsonSerializerCache = new();
	public override OpenApiSchema Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
	{
		var correctedOptions = _jsonSerializerCache.GetOrAdd(options.GetHashCode(), _ =>
		{
			var optionsCopy = new JsonSerializerOptions(options);
			optionsCopy.Converters.Remove(options.Converters.First(c => c is SchemaConverter));
			return optionsCopy;
		});

		return JsonSerializer.Deserialize<OpenApiSchema>(ref reader, correctedOptions)!;
	}

	public override void Write(Utf8JsonWriter writer, OpenApiSchema value, JsonSerializerOptions options)
	{
		using var memoryStream = new MemoryStream();
		using (var textWriter = new StreamWriter(memoryStream, leaveOpen: true))
		{
			value.SerializeAsV31(new OpenApiJsonWriter(textWriter));
			textWriter.Flush();
		}

		memoryStream.Position = 0;
		writer.WriteRawValue(memoryStream.ToArray());
	}
}

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions