diff options
| author | crobibero <cody@robibe.ro> | 2020-08-23 07:53:33 -0600 |
|---|---|---|
| committer | crobibero <cody@robibe.ro> | 2020-08-23 07:53:33 -0600 |
| commit | cb44f16068bb66db7e35e473530c0a85583c2511 (patch) | |
| tree | 0f41bf313fded94e3da067faa84ddffee505613d /MediaBrowser.Common/Json/Converters/JsonNullableInt32Converter.cs | |
| parent | 4a64819277b98ac98ba0051c49fcf0cbfe16319c (diff) | |
| parent | f9bb79285b672e63054b4ab1b49b744606851c34 (diff) | |
Merge remote-tracking branch 'upstream/master' into output-formatters
Diffstat (limited to 'MediaBrowser.Common/Json/Converters/JsonNullableInt32Converter.cs')
| -rw-r--r-- | MediaBrowser.Common/Json/Converters/JsonNullableInt32Converter.cs | 55 |
1 files changed, 55 insertions, 0 deletions
diff --git a/MediaBrowser.Common/Json/Converters/JsonNullableInt32Converter.cs b/MediaBrowser.Common/Json/Converters/JsonNullableInt32Converter.cs new file mode 100644 index 000000000..c1660fe76 --- /dev/null +++ b/MediaBrowser.Common/Json/Converters/JsonNullableInt32Converter.cs @@ -0,0 +1,55 @@ +using System; +using System.Buffers; +using System.Buffers.Text; +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace MediaBrowser.Common.Json.Converters +{ + /// <summary> + /// Converts a nullable int32 object or value to/from JSON. + /// </summary> + public class JsonNullableInt32Converter : JsonConverter<int?> + { + /// <inheritdoc /> + public override int? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + if (reader.TokenType == JsonTokenType.String) + { + ReadOnlySpan<byte> span = reader.HasValueSequence ? reader.ValueSequence.ToArray() : reader.ValueSpan; + if (Utf8Parser.TryParse(span, out int number, out int bytesConsumed) && span.Length == bytesConsumed) + { + return number; + } + + var stringValue = reader.GetString().AsSpan(); + + // value is null or empty, just return null. + if (stringValue.IsEmpty) + { + return null; + } + + if (int.TryParse(stringValue, out number)) + { + return number; + } + } + + return reader.GetInt32(); + } + + /// <inheritdoc /> + public override void Write(Utf8JsonWriter writer, int? value, JsonSerializerOptions options) + { + if (value is null) + { + writer.WriteNullValue(); + } + else + { + writer.WriteNumberValue(value.Value); + } + } + } +} |
