From a75a17f3cd68a6ec0b9a43bf8f655b1c5a8276e3 Mon Sep 17 00:00:00 2001 From: Steve Gordon Date: Tue, 30 Jan 2024 08:11:15 +0000 Subject: [PATCH] Fix serialisation of empty and single item `Fields` instances (#8018) --- .../Core/Infer/Fields/Fields.cs | 2 +- .../Core/Infer/Fields/FieldsConverter.cs | 16 +++++++++++++++- 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/src/Elastic.Clients.Elasticsearch.Shared/Core/Infer/Fields/Fields.cs b/src/Elastic.Clients.Elasticsearch.Shared/Core/Infer/Fields/Fields.cs index 840c6563ef6..debe5562826 100644 --- a/src/Elastic.Clients.Elasticsearch.Shared/Core/Infer/Fields/Fields.cs +++ b/src/Elastic.Clients.Elasticsearch.Shared/Core/Infer/Fields/Fields.cs @@ -27,7 +27,7 @@ public sealed class Fields : IUrlParameter, IEnumerable, IEquatable ListOfFields = new List(); - internal Fields(IEnumerable fieldNames) => ListOfFields = fieldNames.ToList(); + internal Fields(IEnumerable fieldNames) => ListOfFields = new List(fieldNames); private string DebugDisplay => $"Count: {ListOfFields.Count} [" + diff --git a/src/Elastic.Clients.Elasticsearch.Shared/Core/Infer/Fields/FieldsConverter.cs b/src/Elastic.Clients.Elasticsearch.Shared/Core/Infer/Fields/FieldsConverter.cs index 1788f8d1e1a..3c7b65ca352 100644 --- a/src/Elastic.Clients.Elasticsearch.Shared/Core/Infer/Fields/FieldsConverter.cs +++ b/src/Elastic.Clients.Elasticsearch.Shared/Core/Infer/Fields/FieldsConverter.cs @@ -22,7 +22,8 @@ internal sealed class FieldsConverter : JsonConverter Fields fields = reader.GetString(); return fields; } - else if (reader.TokenType == JsonTokenType.StartArray) + + if (reader.TokenType == JsonTokenType.StartArray) { var fields = new List(); while (reader.Read() && reader.TokenType != JsonTokenType.EndArray) @@ -45,6 +46,19 @@ public override void Write(Utf8JsonWriter writer, Fields value, JsonSerializerOp return; } + if (value.ListOfFields.Count == 0) + { + writer.WriteStartObject(); + writer.WriteEndObject(); + return; + } + + if (value.ListOfFields.Count == 1) + { + JsonSerializer.Serialize(writer, value.ListOfFields[0], options); + return; + } + writer.WriteStartArray(); foreach (var field in value.ListOfFields) {