aboutsummaryrefslogtreecommitdiff
path: root/MediaBrowser.Common/Json
diff options
context:
space:
mode:
Diffstat (limited to 'MediaBrowser.Common/Json')
-rw-r--r--MediaBrowser.Common/Json/Converters/JsonDoubleConverter.cs56
-rw-r--r--MediaBrowser.Common/Json/Converters/JsonInt32Converter.cs37
-rw-r--r--MediaBrowser.Common/Json/Converters/JsonInt64Converter.cs56
-rw-r--r--MediaBrowser.Common/Json/Converters/JsonNonStringKeyDictionaryConverter.cs82
-rw-r--r--MediaBrowser.Common/Json/Converters/JsonNonStringKeyDictionaryConverterFactory.cs59
-rw-r--r--MediaBrowser.Common/Json/JsonDefaults.cs34
6 files changed, 298 insertions, 26 deletions
diff --git a/MediaBrowser.Common/Json/Converters/JsonDoubleConverter.cs b/MediaBrowser.Common/Json/Converters/JsonDoubleConverter.cs
new file mode 100644
index 000000000..e5e9f28da
--- /dev/null
+++ b/MediaBrowser.Common/Json/Converters/JsonDoubleConverter.cs
@@ -0,0 +1,56 @@
+using System;
+using System.Buffers;
+using System.Buffers.Text;
+using System.Globalization;
+using System.Text.Json;
+using System.Text.Json.Serialization;
+
+namespace MediaBrowser.Common.Json.Converters
+{
+ /// <summary>
+ /// Double to String JSON converter.
+ /// Web client send quoted doubles.
+ /// </summary>
+ public class JsonDoubleConverter : JsonConverter<double>
+ {
+ /// <summary>
+ /// Read JSON string as double.
+ /// </summary>
+ /// <param name="reader"><see cref="Utf8JsonReader"/>.</param>
+ /// <param name="typeToConvert">Type.</param>
+ /// <param name="options">Options.</param>
+ /// <returns>Parsed value.</returns>
+ public override double Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
+ {
+ if (reader.TokenType == JsonTokenType.String)
+ {
+ // try to parse number directly from bytes
+ var span = reader.HasValueSequence ? reader.ValueSequence.ToArray() : reader.ValueSpan;
+ if (Utf8Parser.TryParse(span, out double number, out var bytesConsumed) && span.Length == bytesConsumed)
+ {
+ return number;
+ }
+
+ // try to parse from a string if the above failed, this covers cases with other escaped/UTF characters
+ if (double.TryParse(reader.GetString(), out number))
+ {
+ return number;
+ }
+ }
+
+ // fallback to default handling
+ return reader.GetDouble();
+ }
+
+ /// <summary>
+ /// Write double to JSON string.
+ /// </summary>
+ /// <param name="writer"><see cref="Utf8JsonWriter"/>.</param>
+ /// <param name="value">Value to write.</param>
+ /// <param name="options">Options.</param>
+ public override void Write(Utf8JsonWriter writer, double value, JsonSerializerOptions options)
+ {
+ writer.WriteStringValue(value.ToString(NumberFormatInfo.InvariantInfo));
+ }
+ }
+}
diff --git a/MediaBrowser.Common/Json/Converters/JsonInt32Converter.cs b/MediaBrowser.Common/Json/Converters/JsonInt32Converter.cs
index fe5dd6cd4..70c375b8c 100644
--- a/MediaBrowser.Common/Json/Converters/JsonInt32Converter.cs
+++ b/MediaBrowser.Common/Json/Converters/JsonInt32Converter.cs
@@ -14,40 +14,27 @@ namespace MediaBrowser.Common.Json.Converters
/// <inheritdoc />
public override int Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
- static void ThrowFormatException() => throw new FormatException("Invalid format for an integer.");
- ReadOnlySpan<byte> span = stackalloc byte[0];
-
- if (reader.HasValueSequence)
- {
- long sequenceLength = reader.ValueSequence.Length;
- Span<byte> stackSpan = stackalloc byte[(int)sequenceLength];
- reader.ValueSequence.CopyTo(stackSpan);
- span = stackSpan;
- }
- else
+ if (reader.TokenType == JsonTokenType.String)
{
- span = reader.ValueSpan;
- }
+ 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;
+ }
- if (!Utf8Parser.TryParse(span, out int number, out _))
- {
- ThrowFormatException();
+ if (int.TryParse(reader.GetString(), out number))
+ {
+ return number;
+ }
}
- return number;
+ return reader.GetInt32();
}
/// <inheritdoc />
public override void Write(Utf8JsonWriter writer, int value, JsonSerializerOptions options)
{
- static void ThrowInvalidOperationException() => throw new InvalidOperationException();
- Span<byte> span = stackalloc byte[16];
- if (Utf8Formatter.TryFormat(value, span, out int bytesWritten))
- {
- writer.WriteStringValue(span.Slice(0, bytesWritten));
- }
-
- ThrowInvalidOperationException();
+ writer.WriteNumberValue(value);
}
}
}
diff --git a/MediaBrowser.Common/Json/Converters/JsonInt64Converter.cs b/MediaBrowser.Common/Json/Converters/JsonInt64Converter.cs
new file mode 100644
index 000000000..d18fd95d5
--- /dev/null
+++ b/MediaBrowser.Common/Json/Converters/JsonInt64Converter.cs
@@ -0,0 +1,56 @@
+using System;
+using System.Buffers;
+using System.Buffers.Text;
+using System.Globalization;
+using System.Text.Json;
+using System.Text.Json.Serialization;
+
+namespace MediaBrowser.Common.Json.Converters
+{
+ /// <summary>
+ /// Long to String JSON converter.
+ /// Javascript does not support 64-bit integers.
+ /// </summary>
+ public class JsonInt64Converter : JsonConverter<long>
+ {
+ /// <summary>
+ /// Read JSON string as int64.
+ /// </summary>
+ /// <param name="reader"><see cref="Utf8JsonReader"/>.</param>
+ /// <param name="type">Type.</param>
+ /// <param name="options">Options.</param>
+ /// <returns>Parsed value.</returns>
+ public override long Read(ref Utf8JsonReader reader, Type type, JsonSerializerOptions options)
+ {
+ if (reader.TokenType == JsonTokenType.String)
+ {
+ // try to parse number directly from bytes
+ var span = reader.HasValueSequence ? reader.ValueSequence.ToArray() : reader.ValueSpan;
+ if (Utf8Parser.TryParse(span, out long number, out var bytesConsumed) && span.Length == bytesConsumed)
+ {
+ return number;
+ }
+
+ // try to parse from a string if the above failed, this covers cases with other escaped/UTF characters
+ if (long.TryParse(reader.GetString(), out number))
+ {
+ return number;
+ }
+ }
+
+ // fallback to default handling
+ return reader.GetInt64();
+ }
+
+ /// <summary>
+ /// Write long to JSON string.
+ /// </summary>
+ /// <param name="writer"><see cref="Utf8JsonWriter"/>.</param>
+ /// <param name="value">Value to write.</param>
+ /// <param name="options">Options.</param>
+ public override void Write(Utf8JsonWriter writer, long value, JsonSerializerOptions options)
+ {
+ writer.WriteStringValue(value.ToString(NumberFormatInfo.InvariantInfo));
+ }
+ }
+}
diff --git a/MediaBrowser.Common/Json/Converters/JsonNonStringKeyDictionaryConverter.cs b/MediaBrowser.Common/Json/Converters/JsonNonStringKeyDictionaryConverter.cs
new file mode 100644
index 000000000..8053461f0
--- /dev/null
+++ b/MediaBrowser.Common/Json/Converters/JsonNonStringKeyDictionaryConverter.cs
@@ -0,0 +1,82 @@
+#nullable enable
+
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using System.Globalization;
+using System.Reflection;
+using System.Text.Json;
+using System.Text.Json.Serialization;
+
+namespace MediaBrowser.Common.Json.Converters
+{
+ /// <summary>
+ /// Converter for Dictionaries without string key.
+ /// TODO This can be removed when System.Text.Json supports Dictionaries with non-string keys.
+ /// </summary>
+ /// <typeparam name="TKey">Type of key.</typeparam>
+ /// <typeparam name="TValue">Type of value.</typeparam>
+ internal sealed class JsonNonStringKeyDictionaryConverter<TKey, TValue> : JsonConverter<IDictionary<TKey, TValue>>
+ {
+ /// <summary>
+ /// Read JSON.
+ /// </summary>
+ /// <param name="reader">The Utf8JsonReader.</param>
+ /// <param name="typeToConvert">The type to convert.</param>
+ /// <param name="options">The json serializer options.</param>
+ /// <returns>Typed dictionary.</returns>
+ /// <exception cref="NotSupportedException">Dictionary key type not supported.</exception>
+ public override IDictionary<TKey, TValue> Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
+ {
+ var convertedType = typeof(Dictionary<,>).MakeGenericType(typeof(string), typeToConvert.GenericTypeArguments[1]);
+ var value = JsonSerializer.Deserialize(ref reader, convertedType, options);
+ var instance = (Dictionary<TKey, TValue>)Activator.CreateInstance(
+ typeToConvert,
+ BindingFlags.Instance | BindingFlags.Public,
+ null,
+ null,
+ CultureInfo.CurrentCulture);
+ var enumerator = (IEnumerator)convertedType.GetMethod("GetEnumerator")!.Invoke(value, null);
+ var parse = typeof(TKey).GetMethod(
+ "Parse",
+ 0,
+ BindingFlags.Public | BindingFlags.Static,
+ null,
+ CallingConventions.Any,
+ new[] { typeof(string) },
+ null);
+ if (parse == null)
+ {
+ throw new NotSupportedException($"{typeof(TKey)} as TKey in IDictionary<TKey, TValue> is not supported.");
+ }
+
+ while (enumerator.MoveNext())
+ {
+ var element = (KeyValuePair<string?, TValue>)enumerator.Current;
+ instance.Add((TKey)parse.Invoke(null, new[] { (object?)element.Key }), element.Value);
+ }
+
+ return instance;
+ }
+
+ /// <summary>
+ /// Write dictionary as Json.
+ /// </summary>
+ /// <param name="writer">The Utf8JsonWriter.</param>
+ /// <param name="value">The dictionary value.</param>
+ /// <param name="options">The Json serializer options.</param>
+ public override void Write(Utf8JsonWriter writer, IDictionary<TKey, TValue> value, JsonSerializerOptions options)
+ {
+ var convertedDictionary = new Dictionary<string?, TValue>(value.Count);
+ foreach (var (k, v) in value)
+ {
+ if (k != null)
+ {
+ convertedDictionary[k.ToString()] = v;
+ }
+ }
+
+ JsonSerializer.Serialize(writer, convertedDictionary, options);
+ }
+ }
+}
diff --git a/MediaBrowser.Common/Json/Converters/JsonNonStringKeyDictionaryConverterFactory.cs b/MediaBrowser.Common/Json/Converters/JsonNonStringKeyDictionaryConverterFactory.cs
new file mode 100644
index 000000000..52f360740
--- /dev/null
+++ b/MediaBrowser.Common/Json/Converters/JsonNonStringKeyDictionaryConverterFactory.cs
@@ -0,0 +1,59 @@
+#nullable enable
+
+using System;
+using System.Collections;
+using System.Globalization;
+using System.Reflection;
+using System.Text.Json;
+using System.Text.Json.Serialization;
+
+namespace MediaBrowser.Common.Json.Converters
+{
+ /// <summary>
+ /// https://github.com/dotnet/runtime/issues/30524#issuecomment-524619972.
+ /// TODO This can be removed when System.Text.Json supports Dictionaries with non-string keys.
+ /// </summary>
+ internal sealed class JsonNonStringKeyDictionaryConverterFactory : JsonConverterFactory
+ {
+ /// <summary>
+ /// Only convert objects that implement IDictionary and do not have string keys.
+ /// </summary>
+ /// <param name="typeToConvert">Type convert.</param>
+ /// <returns>Conversion ability.</returns>
+ public override bool CanConvert(Type typeToConvert)
+ {
+ if (!typeToConvert.IsGenericType)
+ {
+ return false;
+ }
+
+ // Let built in converter handle string keys
+ if (typeToConvert.GenericTypeArguments[0] == typeof(string))
+ {
+ return false;
+ }
+
+ // Only support objects that implement IDictionary
+ return typeToConvert.GetInterface(nameof(IDictionary)) != null;
+ }
+
+ /// <summary>
+ /// Create converter for generic dictionary type.
+ /// </summary>
+ /// <param name="typeToConvert">Type to convert.</param>
+ /// <param name="options">Json serializer options.</param>
+ /// <returns>JsonConverter for given type.</returns>
+ public override JsonConverter CreateConverter(Type typeToConvert, JsonSerializerOptions options)
+ {
+ var converterType = typeof(JsonNonStringKeyDictionaryConverter<,>)
+ .MakeGenericType(typeToConvert.GenericTypeArguments[0], typeToConvert.GenericTypeArguments[1]);
+ var converter = (JsonConverter)Activator.CreateInstance(
+ converterType,
+ BindingFlags.Instance | BindingFlags.Public,
+ null,
+ null,
+ CultureInfo.CurrentCulture);
+ return converter;
+ }
+ }
+}
diff --git a/MediaBrowser.Common/Json/JsonDefaults.cs b/MediaBrowser.Common/Json/JsonDefaults.cs
index 4a6ee0a79..36ab6d900 100644
--- a/MediaBrowser.Common/Json/JsonDefaults.cs
+++ b/MediaBrowser.Common/Json/JsonDefaults.cs
@@ -12,19 +12,51 @@ namespace MediaBrowser.Common.Json
/// <summary>
/// Gets the default <see cref="JsonSerializerOptions" /> options.
/// </summary>
+ /// <remarks>
+ /// When changing these options, update
+ /// Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs
+ /// -> AddJellyfinApi
+ /// -> AddJsonOptions.
+ /// </remarks>
/// <returns>The default <see cref="JsonSerializerOptions" /> options.</returns>
public static JsonSerializerOptions GetOptions()
{
- var options = new JsonSerializerOptions()
+ var options = new JsonSerializerOptions
{
ReadCommentHandling = JsonCommentHandling.Disallow,
WriteIndented = false
};
options.Converters.Add(new JsonGuidConverter());
+ options.Converters.Add(new JsonInt32Converter());
options.Converters.Add(new JsonStringEnumConverter());
+ options.Converters.Add(new JsonNonStringKeyDictionaryConverterFactory());
+ options.Converters.Add(new JsonInt64Converter());
+ options.Converters.Add(new JsonDoubleConverter());
return options;
}
+
+ /// <summary>
+ /// Gets camelCase json options.
+ /// </summary>
+ /// <returns>The camelCase <see cref="JsonSerializerOptions" /> options.</returns>
+ public static JsonSerializerOptions GetCamelCaseOptions()
+ {
+ var options = GetOptions();
+ options.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;
+ return options;
+ }
+
+ /// <summary>
+ /// Gets PascalCase json options.
+ /// </summary>
+ /// <returns>The PascalCase <see cref="JsonSerializerOptions" /> options.</returns>
+ public static JsonSerializerOptions GetPascalCaseOptions()
+ {
+ var options = GetOptions();
+ options.PropertyNamingPolicy = null;
+ return options;
+ }
}
}