|
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 | namespace Elastic.Clients.Elasticsearch;
|
12 | 15 |
|
13 | 16 | [DebuggerDisplay("{DebugDisplay,nq}")]
|
| 17 | +[JsonConverter(typeof(NamesConverter))] |
14 | 18 | public sealed class Names : IEquatable<Names>, IUrlParameter
|
15 | 19 | {
|
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 | + } |
17 | 23 |
|
18 | 24 | public Names(IEnumerable<Name> names)
|
19 | 25 | {
|
@@ -61,3 +67,44 @@ private static bool EqualsAllIds(ICollection<Name> thisIds, ICollection<Name> ot
|
61 | 67 |
|
62 | 68 | public override int GetHashCode() => Value.GetHashCode();
|
63 | 69 | }
|
| 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