Skip to content

Commit a170ce5

Browse files
Fix serialization of Names (#8486) (#8487)
Co-authored-by: Florian Bernd <[email protected]>
1 parent 899ccae commit a170ce5

File tree

1 file changed

+48
-1
lines changed
  • src/Elastic.Clients.Elasticsearch/_Shared/Core/UrlParameters/Name

1 file changed

+48
-1
lines changed

Diff for: src/Elastic.Clients.Elasticsearch/_Shared/Core/UrlParameters/Name/Names.cs

+48-1
Original file line numberDiff line numberDiff line change
@@ -6,14 +6,20 @@
66
using System.Collections.Generic;
77
using System.Diagnostics;
88
using System.Linq;
9+
using System.Text.Json;
10+
using System.Text.Json.Serialization;
11+
912
using Elastic.Transport;
1013

1114
namespace Elastic.Clients.Elasticsearch;
1215

1316
[DebuggerDisplay("{DebugDisplay,nq}")]
17+
[JsonConverter(typeof(NamesConverter))]
1418
public sealed class Names : IEquatable<Names>, IUrlParameter
1519
{
16-
public Names(IEnumerable<string> names) : this(names?.Select(n => (Name)n).ToList()) { }
20+
public Names(IEnumerable<string> names) : this(names?.Select(n => (Name)n).ToList())
21+
{
22+
}
1723

1824
public Names(IEnumerable<Name> names)
1925
{
@@ -61,3 +67,44 @@ private static bool EqualsAllIds(ICollection<Name> thisIds, ICollection<Name> ot
6167

6268
public override int GetHashCode() => Value.GetHashCode();
6369
}
70+
71+
internal sealed class NamesConverter :
72+
JsonConverter<Names>
73+
{
74+
public override Names? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
75+
{
76+
switch (reader.TokenType)
77+
{
78+
case JsonTokenType.Null:
79+
return null;
80+
81+
case JsonTokenType.String:
82+
var name = JsonSerializer.Deserialize<Name>(ref reader, options);
83+
return new Names([name]);
84+
85+
case JsonTokenType.StartArray:
86+
var names = JsonSerializer.Deserialize<List<Name>>(ref reader, options);
87+
return new Names(names);
88+
89+
default:
90+
throw new JsonException("Unexpected token.");
91+
}
92+
}
93+
94+
public override void Write(Utf8JsonWriter writer, Names value, JsonSerializerOptions options)
95+
{
96+
if (value is null)
97+
{
98+
writer.WriteNullValue();
99+
return;
100+
}
101+
102+
if (value.Value.Count == 1)
103+
{
104+
JsonSerializer.Serialize(writer, value.Value[0], options);
105+
return;
106+
}
107+
108+
JsonSerializer.Serialize(writer, value.Value, options);
109+
}
110+
}

0 commit comments

Comments
 (0)