Skip to content

Commit

Permalink
Optimized FieldConverter (#7736)
Browse files Browse the repository at this point in the history
  • Loading branch information
YohDeadfall committed Jul 10, 2023
1 parent 8195e84 commit f181ca7
Showing 1 changed file with 18 additions and 23 deletions.
Expand Up @@ -12,6 +12,9 @@ namespace Elastic.Clients.Elasticsearch;

internal sealed class FieldConverter : JsonConverter<Field>
{
private static readonly JsonEncodedText FieldProperty = JsonEncodedText.Encode("field");
private static readonly JsonEncodedText FormatProperty = JsonEncodedText.Encode("format");

private IElasticsearchClientSettings _settings;

public override void WriteAsPropertyName(Utf8JsonWriter writer, Field value, JsonSerializerOptions options)
Expand Down Expand Up @@ -48,19 +51,19 @@ private static Field ReadObjectField(ref Utf8JsonReader reader)
{
if (reader.TokenType == JsonTokenType.PropertyName)
{
var propertyName = reader.GetString();
reader.Read();

switch (propertyName)
if (reader.ValueTextEquals(FieldProperty.EncodedUtf8Bytes))
{
reader.Read();
field = reader.GetString();
}
else if (reader.ValueTextEquals(FormatProperty.EncodedUtf8Bytes))
{
reader.Read();
format = reader.GetString();
}
else
{
case "field":
field = reader.GetString();
break;
case "format":
format = reader.GetString();
break;
default:
throw new JsonException("Unexpected property while reading `Field`.");
throw new JsonException($"Unexpected property while reading `{nameof(Field)}`.");
}
}
}
Expand All @@ -70,19 +73,13 @@ private static Field ReadObjectField(ref Utf8JsonReader reader)
return new Field(field, format);
}

throw new JsonException("Unable to read `Field` from JSON.");
throw new JsonException($"Unable to read `{nameof(Field)}` from JSON.");
}

public override void Write(Utf8JsonWriter writer, Field value, JsonSerializerOptions options)
{
InitializeSettings(options);

if (value is null)
{
writer.WriteNullValue();
return;
}

var fieldName = _settings.Inferrer.Field(value);

if (string.IsNullOrEmpty(value.Format))
Expand All @@ -92,10 +89,8 @@ public override void Write(Utf8JsonWriter writer, Field value, JsonSerializerOpt
else
{
writer.WriteStartObject();
writer.WritePropertyName("field");
writer.WriteStringValue(fieldName);
writer.WritePropertyName("format");
writer.WriteStringValue(value.Format);
writer.WriteString(FieldProperty, fieldName);
writer.WriteString(FormatProperty, value.Format);
writer.WriteEndObject();
}
}
Expand Down

0 comments on commit f181ca7

Please sign in to comment.