From b7533abf8507c21ba097bb9c4be061c9865b2420 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 19f7e64c788..9e525c6e8f1 100644 --- a/src/Elastic.Clients.Elasticsearch/_Shared/Core/UrlParameters/Name/Names.cs +++ b/src/Elastic.Clients.Elasticsearch/_Shared/Core/UrlParameters/Name/Names.cs @@ -6,6 +6,9 @@ using System.Collections.Generic; using System.Diagnostics; using System.Linq; +using System.Text.Json; +using System.Text.Json.Serialization; + using Elastic.Transport; #if ELASTICSEARCH_SERVERLESS @@ -15,9 +18,12 @@ namespace Elastic.Clients.Elasticsearch; #endif [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) { @@ -65,3 +71,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); + } +}