Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

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

Copy link
Copy link
@Poltuu

Description

@Poltuu
Issue body actions

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());
	}
}
Reactions are currently unavailable

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

      Morty Proxy This is a proxified and sanitized view of the page, visit original site.