Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,9 @@
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text.Json;
using System.Text.Json.Serialization;

using Elastic.Transport;

#if ELASTICSEARCH_SERVERLESS
Expand All @@ -15,9 +18,12 @@ namespace Elastic.Clients.Elasticsearch;
#endif

[DebuggerDisplay("{DebugDisplay,nq}")]
[JsonConverter(typeof(NamesConverter))]
public sealed class Names : IEquatable<Names>, IUrlParameter
{
public Names(IEnumerable<string> names) : this(names?.Select(n => (Name)n).ToList()) { }
public Names(IEnumerable<string> names) : this(names?.Select(n => (Name)n).ToList())
{
}

public Names(IEnumerable<Name> names)
{
Expand Down Expand Up @@ -65,3 +71,44 @@ private static bool EqualsAllIds(ICollection<Name> thisIds, ICollection<Name> ot

public override int GetHashCode() => Value.GetHashCode();
}

internal sealed class NamesConverter :
JsonConverter<Names>
{
public override Names? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
switch (reader.TokenType)
{
case JsonTokenType.Null:
return null;

case JsonTokenType.String:
var name = JsonSerializer.Deserialize<Name>(ref reader, options);
return new Names([name]);

case JsonTokenType.StartArray:
var names = JsonSerializer.Deserialize<List<Name>>(ref reader, options);
return new Names(names);

default:
throw new JsonException("Unexpected token.");
}
}

public override void Write(Utf8JsonWriter writer, Names value, JsonSerializerOptions options)
{
if (value is null)
{
writer.WriteNullValue();
return;
}

if (value.Value.Count == 1)
{
JsonSerializer.Serialize(writer, value.Value[0], options);
return;
}

JsonSerializer.Serialize(writer, value.Value, options);
}
}