66using System . Collections . Generic ;
77using System . Diagnostics ;
88using System . Linq ;
9+ using System . Text . Json ;
10+ using System . Text . Json . Serialization ;
11+
912using Elastic . Transport ;
1013
1114#if ELASTICSEARCH_SERVERLESS
@@ -15,9 +18,12 @@ namespace Elastic.Clients.Elasticsearch;
1518#endif
1619
1720[ DebuggerDisplay ( "{DebugDisplay,nq}" ) ]
21+ [ JsonConverter ( typeof ( NamesConverter ) ) ]
1822public sealed class Names : IEquatable < Names > , IUrlParameter
1923{
20- public Names ( IEnumerable < string > names ) : this ( names ? . Select ( n => ( Name ) n ) . ToList ( ) ) { }
24+ public Names ( IEnumerable < string > names ) : this ( names ? . Select ( n => ( Name ) n ) . ToList ( ) )
25+ {
26+ }
2127
2228 public Names ( IEnumerable < Name > names )
2329 {
@@ -65,3 +71,44 @@ private static bool EqualsAllIds(ICollection<Name> thisIds, ICollection<Name> ot
6571
6672 public override int GetHashCode ( ) => Value . GetHashCode ( ) ;
6773}
74+
75+ internal sealed class NamesConverter :
76+ JsonConverter < Names >
77+ {
78+ public override Names ? Read ( ref Utf8JsonReader reader , Type typeToConvert , JsonSerializerOptions options )
79+ {
80+ switch ( reader . TokenType )
81+ {
82+ case JsonTokenType . Null :
83+ return null ;
84+
85+ case JsonTokenType . String :
86+ var name = JsonSerializer . Deserialize < Name > ( ref reader , options ) ;
87+ return new Names ( [ name ] ) ;
88+
89+ case JsonTokenType . StartArray :
90+ var names = JsonSerializer . Deserialize < List < Name > > ( ref reader , options ) ;
91+ return new Names ( names ) ;
92+
93+ default :
94+ throw new JsonException ( "Unexpected token." ) ;
95+ }
96+ }
97+
98+ public override void Write ( Utf8JsonWriter writer , Names value , JsonSerializerOptions options )
99+ {
100+ if ( value is null )
101+ {
102+ writer . WriteNullValue ( ) ;
103+ return ;
104+ }
105+
106+ if ( value . Value . Count == 1 )
107+ {
108+ JsonSerializer . Serialize ( writer , value . Value [ 0 ] , options ) ;
109+ return ;
110+ }
111+
112+ JsonSerializer . Serialize ( writer , value . Value , options ) ;
113+ }
114+ }
0 commit comments