Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Complted buckets JSON converter #7738

Merged
merged 3 commits into from
Jul 10, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
33 changes: 21 additions & 12 deletions src/Elastic.Clients.Elasticsearch/Serialization/UnionConverter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -122,12 +122,6 @@ private class DerivedUnionConverterInner<TType, TItem1, TItem2> : JsonConverter<
public override void Write(Utf8JsonWriter writer, TType value,
JsonSerializerOptions options)
{
if (value is null)
YohDeadfall marked this conversation as resolved.
Show resolved Hide resolved
{
writer.WriteNullValue();
return;
}

if (value.Item1 is not null)
{
JsonSerializer.Serialize(writer, value.Item1, value.Item1.GetType(), options);
Expand Down Expand Up @@ -214,15 +208,30 @@ private class BucketsConverter<TBucket> : JsonConverter<Buckets<TBucket>>
{
public override Buckets<TBucket>? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
// TODO - Read ahead to establish the type - For now, hardcoded for lists
return reader.TokenType switch
{
JsonTokenType.Null => null,
JsonTokenType.StartArray => new(JsonSerializer.Deserialize<IReadOnlyCollection<TBucket>>(ref reader, options)),
JsonTokenType.StartObject => new(JsonSerializer.Deserialize<IReadOnlyDictionary<string, TBucket>>(ref reader, options)),
_ => throw new JsonException("Invalid bucket type")
};
}

var bucketType = typeToConvert.GetGenericArguments()[0];
public override void Write(Utf8JsonWriter writer, Buckets<TBucket> value, JsonSerializerOptions options)
{
if (value.Item1 is { } item1)
{
JsonSerializer.Serialize(writer, item1, options);
return;
}

var item = JsonSerializer.Deserialize(ref reader, typeof(IReadOnlyCollection<TBucket>), options);
if (value.Item2 is { } item2)
{
JsonSerializer.Serialize(writer, item2, options);
return;
}

return (Buckets<TBucket>)Activator.CreateInstance(typeof(Buckets<>).MakeGenericType(bucketType), item);
writer.WriteNullValue();
}

public override void Write(Utf8JsonWriter writer, Buckets<TBucket> value, JsonSerializerOptions options) => throw new NotImplementedException();
}
}