6
6
using System . Collections . Generic ;
7
7
using System . Diagnostics ;
8
8
using System . Linq ;
9
+ using System . Text . Json ;
10
+ using System . Text . Json . Serialization ;
11
+
9
12
using Elastic . Transport ;
10
13
11
14
#if ELASTICSEARCH_SERVERLESS
@@ -15,9 +18,12 @@ namespace Elastic.Clients.Elasticsearch;
15
18
#endif
16
19
17
20
[ DebuggerDisplay ( "{DebugDisplay,nq}" ) ]
21
+ [ JsonConverter ( typeof ( NamesConverter ) ) ]
18
22
public sealed class Names : IEquatable < Names > , IUrlParameter
19
23
{
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
+ }
21
27
22
28
public Names ( IEnumerable < Name > names )
23
29
{
@@ -65,3 +71,44 @@ private static bool EqualsAllIds(ICollection<Name> thisIds, ICollection<Name> ot
65
71
66
72
public override int GetHashCode ( ) => Value . GetHashCode ( ) ;
67
73
}
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