using System.Reflection; using System.Text.Json; namespace SPTarkov.Common.Extensions; public static class ObjectExtensions { private static readonly Dictionary> _indexedProperties = new(); private static readonly Lock _indexedPropertiesLockObject = new(); private static bool TryGetCachedProperty(Type type, string key, out PropertyInfo cachedProperty) { lock (_indexedPropertiesLockObject) { if (!_indexedProperties.TryGetValue(type, out var properties)) { properties = type.GetProperties().ToDictionary(prop => prop.GetJsonName(), prop => prop); _indexedProperties.Add(type, properties); } return properties.TryGetValue(key, out cachedProperty); } } /// /// CARE WHEN USING THIS, THIS IS TO GET PROP ON A TYPE /// /// /// /// /// /// public static bool ContainsJsonProp(this object? obj, T key) { ArgumentNullException.ThrowIfNull(obj); ArgumentNullException.ThrowIfNull(key); return TryGetCachedProperty(obj.GetType(), key.ToString(), out _); } public static T? GetByJsonProp(this object? obj, string? toLower) { ArgumentNullException.ThrowIfNull(obj); ArgumentNullException.ThrowIfNull(toLower); if (!TryGetCachedProperty(obj.GetType(), toLower, out var cachedProperty)) { return default; } return (T?) cachedProperty.GetValue(obj); } public static List GetAllPropValuesAsList(this object? obj) { ArgumentNullException.ThrowIfNull(obj); var list = obj.GetType().GetProperties(); var result = new List(); foreach (var prop in list) { result.Add(prop.GetValue(obj)); } return result; } public static Dictionary GetAllPropsAsDict(this object? obj) { var props = obj.GetType().GetProperties(); return props.ToDictionary(prop => prop.Name, prop => prop.GetValue(obj)); } public static T ToObject(this JsonElement element) { var json = element.GetRawText(); return JsonSerializer.Deserialize(json); } }