Skip to content

Commit

Permalink
fix: Fix LyricsJava workaround
Browse files Browse the repository at this point in the history
  • Loading branch information
angelobreuer committed Mar 16, 2024
1 parent 988512f commit 3912c20
Showing 1 changed file with 14 additions and 35 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

using System.Collections.Immutable;
using System.Net;
using System.Net.Http.Json;
using System.Text.Json;
using System.Text.Json.Nodes;
using System.Text.Json.Serialization.Metadata;
Expand Down Expand Up @@ -127,45 +128,23 @@ file static class LyricsJavaWorkaround
{
public static async Task<T?> ReadFromJsonWithWorkaroundAsync<T>(this HttpContent content, JsonTypeInfo<T> jsonTypeInfo, CancellationToken cancellationToken = default)
{
// FIXME: LyricsJava somehow returns the type property twice in the object
cancellationToken.ThrowIfCancellationRequested();

T? Parse(ReadOnlySpan<byte> value)
{
var jsonObject = new JsonObject();
var utf8JsonReader = new Utf8JsonReader(value);
var isFirst = true;
using var jsonObject = await content
.ReadFromJsonAsync<JsonDocument>(cancellationToken: cancellationToken)
.ConfigureAwait(false);

if (!utf8JsonReader.Read())
{
throw new JsonException("Unexpected EOF", new EndOfStreamException());
}
var fixedJsonObject = new JsonObject { ["type"] = JsonValue.Create(jsonObject!.RootElement.GetProperty("type")), };

while (utf8JsonReader.Read() && utf8JsonReader.TokenType is not JsonTokenType.EndObject)
foreach (var element in jsonObject.RootElement.EnumerateObject().Where(x => !x.Name.Equals("type", StringComparison.Ordinal)))
{
fixedJsonObject.Add(element.Name, element.Value.ValueKind switch
{
var propertyName = utf8JsonReader.GetString()!;

if (!utf8JsonReader.Read())
{
throw new JsonException("Unexpected EOF", new EndOfStreamException());
}

if (!isFirst && propertyName.Equals("type", StringComparison.Ordinal))
{
continue; // Fix duplicate property
}

jsonObject[propertyName] = JsonNode.Parse(ref utf8JsonReader);
isFirst = true;
}

return jsonObject.Deserialize(jsonTypeInfo);
JsonValueKind.Object => JsonObject.Create(element.Value),
JsonValueKind.Array => JsonArray.Create(element.Value),
JsonValueKind.True or JsonValueKind.False or JsonValueKind.String or JsonValueKind.Number => JsonValue.Create(element.Value),
_ => JsonValue.Create((string?)null),
});
}

var jsonObject = await content
.ReadAsByteArrayAsync(cancellationToken)
.ConfigureAwait(false);

return Parse(jsonObject);
return fixedJsonObject.Deserialize(jsonTypeInfo);
}
}

0 comments on commit 3912c20

Please sign in to comment.