From b86d8e8fad9d12a5c2ae4551c4a62f0a40ba9fdd Mon Sep 17 00:00:00 2001 From: Florian Bernd Date: Tue, 8 Apr 2025 15:31:12 +0200 Subject: [PATCH] Fix serialization of `Names` (#8486) --- .../_Shared/Core/UrlParameters/Name/Names.cs | 49 ++++++++++++++++++- 1 file changed, 48 insertions(+), 1 deletion(-) diff --git a/src/Elastic.Clients.Elasticsearch/_Shared/Core/UrlParameters/Name/Names.cs b/src/Elastic.Clients.Elasticsearch/_Shared/Core/UrlParameters/Name/Names.cs index 0cd673b3a4..63b058d3e2 100644 --- a/src/Elastic.Clients.Elasticsearch/_Shared/Core/UrlParameters/Name/Names.cs +++ b/src/Elastic.Clients.Elasticsearch/_Shared/Core/UrlParameters/Name/Names.cs @@ -6,14 +6,20 @@ using System.Collections.Generic; using System.Diagnostics; using System.Linq; +using System.Text.Json; +using System.Text.Json.Serialization; + using Elastic.Transport; namespace Elastic.Clients.Elasticsearch; [DebuggerDisplay("{DebugDisplay,nq}")] +[JsonConverter(typeof(NamesConverter))] public sealed class Names : IEquatable, IUrlParameter { - public Names(IEnumerable names) : this(names?.Select(n => (Name)n).ToList()) { } + public Names(IEnumerable names) : this(names?.Select(n => (Name)n).ToList()) + { + } public Names(IEnumerable names) { @@ -61,3 +67,44 @@ private static bool EqualsAllIds(ICollection thisIds, ICollection ot public override int GetHashCode() => Value.GetHashCode(); } + +internal sealed class NamesConverter : + JsonConverter +{ + public override Names? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + switch (reader.TokenType) + { + case JsonTokenType.Null: + return null; + + case JsonTokenType.String: + var name = JsonSerializer.Deserialize(ref reader, options); + return new Names([name]); + + case JsonTokenType.StartArray: + var names = JsonSerializer.Deserialize>(ref reader, options); + return new Names(names); + + default: + throw new JsonException("Unexpected token."); + } + } + + public override void Write(Utf8JsonWriter writer, Names value, JsonSerializerOptions options) + { + if (value is null) + { + writer.WriteNullValue(); + return; + } + + if (value.Value.Count == 1) + { + JsonSerializer.Serialize(writer, value.Value[0], options); + return; + } + + JsonSerializer.Serialize(writer, value.Value, options); + } +}