Merge pull request #4715 from crobibero/hdhr-json-bool

Add number to bool json converter
This commit is contained in:
Claus Vium 2020-12-08 08:58:01 +01:00 committed by GitHub
commit 0aad17554c
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 58 additions and 0 deletions

View File

@ -8,10 +8,12 @@ using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading;
using System.Threading.Tasks;
using MediaBrowser.Common.Configuration;
using MediaBrowser.Common.Extensions;
using MediaBrowser.Common.Json.Converters;
using MediaBrowser.Common.Net;
using MediaBrowser.Controller;
using MediaBrowser.Controller.Configuration;
@ -340,8 +342,10 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun
public string URL { get; set; }
[JsonConverter(typeof(JsonBoolNumberConverter))]
public bool Favorite { get; set; }
[JsonConverter(typeof(JsonBoolNumberConverter))]
public bool DRM { get; set; }
public int HD { get; set; }

View File

@ -0,0 +1,30 @@
using System;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace MediaBrowser.Common.Json.Converters
{
/// <summary>
/// Converts a number to a boolean.
/// This is needed for HDHomerun.
/// </summary>
public class JsonBoolNumberConverter : JsonConverter<bool>
{
/// <inheritdoc />
public override bool Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
if (reader.TokenType == JsonTokenType.Number)
{
return Convert.ToBoolean(reader.GetInt32());
}
return reader.GetBoolean();
}
/// <inheritdoc />
public override void Write(Utf8JsonWriter writer, bool value, JsonSerializerOptions options)
{
JsonSerializer.Serialize(writer, value, options);
}
}
}

View File

@ -43,6 +43,7 @@ namespace MediaBrowser.Common.Json
options.Converters.Add(new JsonVersionConverter());
options.Converters.Add(new JsonStringEnumConverter());
options.Converters.Add(new JsonNullableStructConverterFactory());
options.Converters.Add(new JsonBoolNumberConverter());
return options;
}

View File

@ -0,0 +1,23 @@
using System.Text.Json;
using MediaBrowser.Common.Json.Converters;
using Xunit;
namespace Jellyfin.Common.Tests.Json
{
public static class JsonBoolNumberTests
{
[Theory]
[InlineData("1", true)]
[InlineData("0", false)]
[InlineData("2", true)]
[InlineData("true", true)]
[InlineData("false", false)]
public static void Deserialize_Number_Valid_Success(string input, bool? output)
{
var options = new JsonSerializerOptions();
options.Converters.Add(new JsonBoolNumberConverter());
var value = JsonSerializer.Deserialize<bool>(input, options);
Assert.Equal(value, output);
}
}
}