KeyValuePairConverter<TKey, TValue>
using System.Collections.Generic;
namespace System.Text.Json.Serialization.Converters
{
internal sealed class KeyValuePairConverter<TKey, TValue> : JsonValueConverter<KeyValuePair<TKey, TValue>>
{
private const string KeyName = "Key";
private const string ValueName = "Value";
private static readonly JsonEncodedText _keyName = JsonEncodedText.Encode("Key", null);
private static readonly JsonEncodedText _valueName = JsonEncodedText.Encode("Value", null);
internal override bool OnTryRead(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options, ref ReadStack state, out KeyValuePair<TKey, TValue> value)
{
if (reader.TokenType != JsonTokenType.StartObject)
ThrowHelper.ThrowJsonException(null);
TKey key = default(TKey);
bool flag = false;
TValue value2 = default(TValue);
bool flag2 = false;
ref reader.ReadWithVerify();
if (reader.TokenType != JsonTokenType.PropertyName)
ThrowHelper.ThrowJsonException(null);
string string = reader.GetString();
if (string == "Key") {
ref reader.ReadWithVerify();
key = JsonSerializer.Deserialize<TKey>(ref reader, options, ref state, "Key");
flag = true;
} else if (string == "Value") {
ref reader.ReadWithVerify();
value2 = JsonSerializer.Deserialize<TValue>(ref reader, options, ref state, "Value");
flag2 = true;
} else {
ThrowHelper.ThrowJsonException(null);
}
ref reader.ReadWithVerify();
if (reader.TokenType != JsonTokenType.PropertyName)
ThrowHelper.ThrowJsonException(null);
string = reader.GetString();
if (string == "Key") {
ref reader.ReadWithVerify();
key = JsonSerializer.Deserialize<TKey>(ref reader, options, ref state, "Key");
flag = true;
} else if (string == "Value") {
ref reader.ReadWithVerify();
value2 = JsonSerializer.Deserialize<TValue>(ref reader, options, ref state, "Value");
flag2 = true;
} else {
ThrowHelper.ThrowJsonException(null);
}
if (!flag || !flag2)
ThrowHelper.ThrowJsonException(null);
ref reader.ReadWithVerify();
if (reader.TokenType != JsonTokenType.EndObject)
ThrowHelper.ThrowJsonException(null);
value = new KeyValuePair<TKey, TValue>(key, value2);
return true;
}
internal override bool OnTryWrite(Utf8JsonWriter writer, KeyValuePair<TKey, TValue> value, JsonSerializerOptions options, ref WriteStack state)
{
writer.WriteStartObject();
writer.WritePropertyName(_keyName);
JsonSerializer.Serialize<TKey>(writer, value.Key, options, ref state, "Key");
writer.WritePropertyName(_valueName);
JsonSerializer.Serialize<TValue>(writer, value.Value, options, ref state, "Value");
writer.WriteEndObject();
return true;
}
}
}