1
0
Fork 0
mirror of https://github.com/Ellpeck/MLEM.git synced 2024-11-25 22:18:34 +01:00

use the known type in StaticJsonConverter

This commit is contained in:
Ell 2021-03-13 03:20:38 +01:00
parent abcdcd21cc
commit a0609e66eb

View file

@ -7,7 +7,7 @@ using Newtonsoft.Json;
namespace MLEM.Data.Json {
/// <summary>
/// A <see cref="JsonConverter{T}"/> that doesn't actually serialize the object, but instead serializes the name given to it by the underlying <see cref="Dictionary{T,T}"/>.
/// Optionally, the name of a <see cref="Dictionary{TKey,TValue}"/> can be passed to this converter when used in the <see cref="JsonConverterAttribute"/> by passing the arguments for the <see cref="StaticJsonConverter{T}(string,string)"/> constructor as <see cref="JsonConverterAttribute.ConverterParameters"/>.
/// Optionally, the name of a <see cref="Dictionary{TKey,TValue}"/> can be passed to this converter when used in the <see cref="JsonConverterAttribute"/> by passing the arguments for the <see cref="StaticJsonConverter{T}(Type,string)"/> constructor as <see cref="JsonConverterAttribute.ConverterParameters"/>.
/// </summary>
/// <typeparam name="T">The type of the object to convert</typeparam>
public class StaticJsonConverter<T> : JsonConverter<T> {
@ -27,10 +27,10 @@ namespace MLEM.Data.Json {
/// <summary>
/// Creates a new static json converter by finding the underlying <see cref="Dictionary{TKey,TValue}"/> from the given type and member name
/// </summary>
/// <param name="typeName">The name of the type that the dictionary is in</param>
/// <param name="type">The type that the dictionary is declared in</param>
/// <param name="memberName">The name of the dictionary itself</param>
public StaticJsonConverter(string typeName, string memberName) :
this(GetEntries(typeName, memberName)) {
public StaticJsonConverter(Type type, string memberName) :
this(GetEntries(type, memberName)) {
}
/// <inheritdoc />
@ -49,9 +49,8 @@ namespace MLEM.Data.Json {
return ret;
}
private static Dictionary<string, T> GetEntries(string typeName, string memberName) {
private static Dictionary<string, T> GetEntries(Type type, string memberName) {
const BindingFlags flags = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic;
var type = Type.GetType(typeName) ?? throw new ArgumentException($"Type {typeName} does not exist", nameof(typeName));
var value = type.GetProperty(memberName, flags)?.GetValue(null) ?? type.GetField(memberName, flags)?.GetValue(null);
if (value == null)
throw new ArgumentException($"There is no property or field value for name {memberName}", nameof(memberName));