Skip to content

Allow KeyValuePairConverter to work with non IUrlParameter keys #8568

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jun 13, 2025
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 @@ -4,9 +4,9 @@

using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text.Json;
using System.Text.Json.Serialization;

using Elastic.Transport;

namespace Elastic.Clients.Elasticsearch.Serialization;
Expand All @@ -17,9 +17,9 @@ internal sealed class KeyValuePairConverterFactory : JsonConverterFactory

public KeyValuePairConverterFactory(IElasticsearchClientSettings settings) => _settings = settings;

public override bool CanConvert(Type typeToConvert) => typeToConvert.IsGenericType
&& typeToConvert.Name == typeof(KeyValuePair<,>).Name
&& typeof(IUrlParameter).IsAssignableFrom(typeToConvert.GetGenericArguments()[0]);
public override bool CanConvert(Type typeToConvert) =>
typeToConvert.IsGenericType &&
typeToConvert.GetGenericTypeDefinition() == typeof(KeyValuePair<,>);

public override JsonConverter CreateConverter(
Type type,
Expand All @@ -31,7 +31,7 @@ public override JsonConverter CreateConverter(
return (JsonConverter)Activator.CreateInstance(typeof(KeyValuePairConverter<,>).MakeGenericType(itemOneType, itemTwoType), _settings);
}

private class KeyValuePairConverter<TItem1, TItem2> : JsonConverter<KeyValuePair<TItem1, TItem2>> where TItem1 : class, IUrlParameter
private class KeyValuePairConverter<TItem1, TItem2> : JsonConverter<KeyValuePair<TItem1, TItem2>>
{
private readonly IElasticsearchClientSettings _settings;

Expand All @@ -58,7 +58,16 @@ public override void Write(Utf8JsonWriter writer, KeyValuePair<TItem1, TItem2> v
JsonSerializerOptions options)
{
writer.WriteStartObject();
writer.WritePropertyName(value.Key.GetString(_settings));

if (value.Key is IUrlParameter parameter)
{
writer.WritePropertyName(parameter.GetString(_settings));
}
else
{
writer.WritePropertyName(value.Key.ToString());
}

JsonSerializer.Serialize<TItem2>(writer, value.Value, options);
writer.WriteEndObject();
}
Expand Down
Loading