punish v6.8.18.0
This commit is contained in:
commit
e786325cda
322 changed files with 554232 additions and 0 deletions
|
@ -0,0 +1,44 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.ObjectModel;
|
||||
using System.Linq;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace Questionable.Model.Common.Converter;
|
||||
|
||||
public abstract class EnumConverter<T> : JsonConverter<T> where T : Enum
|
||||
{
|
||||
private readonly ReadOnlyDictionary<T, string> _enumToString;
|
||||
|
||||
private readonly ReadOnlyDictionary<string, T> _stringToEnum;
|
||||
|
||||
protected EnumConverter(IReadOnlyDictionary<T, string> values)
|
||||
{
|
||||
_enumToString = ((values is IDictionary<T, string> dictionary) ? new ReadOnlyDictionary<T, string>(dictionary) : new ReadOnlyDictionary<T, string>(values.ToDictionary<KeyValuePair<T, string>, T, string>((KeyValuePair<T, string> x) => x.Key, (KeyValuePair<T, string> x) => x.Value)));
|
||||
_stringToEnum = new ReadOnlyDictionary<string, T>(_enumToString.ToDictionary<KeyValuePair<T, string>, string, T>((KeyValuePair<T, string> x) => x.Value, (KeyValuePair<T, string> x) => x.Key));
|
||||
}
|
||||
|
||||
public override T? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
|
||||
{
|
||||
if (reader.TokenType != JsonTokenType.String)
|
||||
{
|
||||
throw new JsonException();
|
||||
}
|
||||
string text = reader.GetString();
|
||||
if (text == null)
|
||||
{
|
||||
throw new JsonException();
|
||||
}
|
||||
if (!_stringToEnum.TryGetValue(text, out var value))
|
||||
{
|
||||
throw new JsonException();
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
public override void Write(Utf8JsonWriter writer, T value, JsonSerializerOptions options)
|
||||
{
|
||||
writer.WriteStringValue(_enumToString[value]);
|
||||
}
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue