| | | 1 | | // Licensed to the .NET Foundation under one or more agreements. |
| | | 2 | | // The .NET Foundation licenses this file to you under the MIT license. |
| | | 3 | | |
| | | 4 | | using System.Diagnostics; |
| | | 5 | | using System.Text.Json.Nodes; |
| | | 6 | | using System.Text.Json.Schema; |
| | | 7 | | |
| | | 8 | | namespace System.Text.Json.Serialization.Converters |
| | | 9 | | { |
| | | 10 | | internal sealed class UriConverter : JsonPrimitiveConverter<Uri?> |
| | | 11 | | { |
| | | 12 | | public override Uri? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) |
| | 634 | 13 | | { |
| | 634 | 14 | | return reader.TokenType is JsonTokenType.Null ? null : ReadCore(ref reader); |
| | 176 | 15 | | } |
| | | 16 | | |
| | | 17 | | public override void Write(Utf8JsonWriter writer, Uri? value, JsonSerializerOptions options) |
| | 0 | 18 | | { |
| | 0 | 19 | | if (value is null) |
| | 0 | 20 | | { |
| | 0 | 21 | | writer.WriteNullValue(); |
| | 0 | 22 | | return; |
| | | 23 | | } |
| | | 24 | | |
| | 0 | 25 | | writer.WriteStringValue(value.OriginalString); |
| | 0 | 26 | | } |
| | | 27 | | |
| | | 28 | | internal override Uri ReadAsPropertyNameCore(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOption |
| | 0 | 29 | | { |
| | 0 | 30 | | Debug.Assert(reader.TokenType is JsonTokenType.PropertyName); |
| | 0 | 31 | | return ReadCore(ref reader); |
| | 0 | 32 | | } |
| | | 33 | | |
| | | 34 | | private static Uri ReadCore(ref Utf8JsonReader reader) |
| | 634 | 35 | | { |
| | 634 | 36 | | string? uriString = reader.GetString(); |
| | | 37 | | |
| | 176 | 38 | | if (!Uri.TryCreate(uriString, UriKind.RelativeOrAbsolute, out Uri? value)) |
| | 0 | 39 | | { |
| | 0 | 40 | | ThrowHelper.ThrowJsonException(); |
| | | 41 | | } |
| | | 42 | | |
| | 176 | 43 | | return value; |
| | 176 | 44 | | } |
| | | 45 | | |
| | | 46 | | internal override void WriteAsPropertyNameCore(Utf8JsonWriter writer, Uri value, JsonSerializerOptions options, |
| | 0 | 47 | | { |
| | 0 | 48 | | ArgumentNullException.ThrowIfNull(value); |
| | | 49 | | |
| | 0 | 50 | | writer.WritePropertyName(value.OriginalString); |
| | 0 | 51 | | } |
| | | 52 | | |
| | | 53 | | internal override JsonSchema? GetSchema(JsonNumberHandling _) => |
| | 0 | 54 | | new() { Type = JsonSchemaType.String, Format = "uri" }; |
| | | 55 | | } |
| | | 56 | | } |