From e8cc3ae1553821e6357dac3f5d36c49bb869f5f7 Mon Sep 17 00:00:00 2001 From: Florian Bernd Date: Tue, 9 Apr 2024 15:35:50 +0200 Subject: [PATCH] Fix serialization of `OpType` (#8105) --- .../Types/OpType.cs | 28 +++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/src/Elastic.Clients.Elasticsearch.Shared/Types/OpType.cs b/src/Elastic.Clients.Elasticsearch.Shared/Types/OpType.cs index 32dd006f264..08e1887ae8f 100644 --- a/src/Elastic.Clients.Elasticsearch.Shared/Types/OpType.cs +++ b/src/Elastic.Clients.Elasticsearch.Shared/Types/OpType.cs @@ -2,6 +2,10 @@ // Elasticsearch B.V licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. +using System; +using System.Text.Json; +using System.Text.Json.Serialization; + using Elastic.Transport; #if ELASTICSEARCH_SERVERLESS @@ -10,6 +14,7 @@ namespace Elastic.Clients.Elasticsearch.Serverless; namespace Elastic.Clients.Elasticsearch; #endif +[JsonConverter(typeof(OpTypeConverter))] public partial struct OpType : IStringable { public static OpType Index = new("index"); @@ -23,3 +28,26 @@ public partial struct OpType : IStringable public string GetString() => Value ?? string.Empty; } + +internal sealed class OpTypeConverter : + JsonConverter +{ + public override OpType Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + if (reader.TokenType != JsonTokenType.String) + { + throw new JsonException("Unexpected token."); + } + + var value = reader.GetString(); + + return value switch + { + "index" => OpType.Index, + "create" => OpType.Create, + _ => throw new JsonException($"Unsupported value '{value}' for '{nameof(OpType)}' enum.") + }; + } + + public override void Write(Utf8JsonWriter writer, OpType value, JsonSerializerOptions options) => writer.WriteStringValue(value.Value); +}