public static bool TryGetProperty(Json.JsonElement e, string name, out string value) { if (e.TryGetProperty(name, out var v)) { value = v.GetString(); return(true); } value = default; return(false); }
public bool TryGet <T>(string key, out T value) { if (storage.TryGetValue(key, out object target)) { if (target == null) { value = default(T); return(true); } log.Debug($"Get: Key: '{key}', RequiredType: '{typeof(T).FullName}', ActualType: '{target.GetType().FullName}'."); if (target is T targetValue) { value = targetValue; return(true); } JsonElement element = (JsonElement)target; if (typeof(T) == typeof(string)) { value = (T)(object)element.GetString(); return(true); } if (typeof(T) == typeof(int)) { value = (T)(object)element.GetInt32(); return(true); } if (typeof(T) == typeof(long)) { value = (T)(object)element.GetInt64(); return(true); } if (typeof(T) == typeof(decimal)) { value = (T)(object)element.GetDecimal(); return(true); } if (typeof(T) == typeof(double)) { value = (T)(object)element.GetDouble(); return(true); } if (typeof(T) == typeof(bool)) { value = (T)(object)element.GetBoolean(); return(true); } if (typeof(T) == typeof(IKey)) { if (element.ValueKind == JsonValueKind.Null) { value = default(T); return(true); } string type = element.GetProperty("Type").GetString(); if (element.TryGetProperty("Guid", out JsonElement rawGuid)) { string rawGuidValue = rawGuid.GetString(); if (rawGuidValue == null) { value = (T)(object)GuidKey.Empty(type); } else { value = (T)(object)GuidKey.Create(Guid.Parse(rawGuidValue), type); } return(true); } else if (element.TryGetProperty("Identifier", out JsonElement rawIdentifier)) { string rawIdentifierValue = rawIdentifier.GetString(); if (rawIdentifierValue == null) { value = (T)(object)StringKey.Empty(type); } else { value = (T)(object)StringKey.Create(rawIdentifierValue, type); } return(true); } } if (typeof(T) == typeof(Color)) { byte[] parts = element.GetString().Split(new char[] { ';' }).Select(p => Byte.Parse(p)).ToArray(); value = (T)(object)Color.FromArgb(parts[0], parts[1], parts[2], parts[3]); log.Debug($"Get: Color: '{value}'."); return(true); } if (typeof(T) == typeof(Price)) { log.Debug($"Get: Price value type: '{element.GetProperty("Value").GetType().FullName}'."); decimal priceValue = element.GetProperty("Value").GetDecimal(); string priceCurrency = element.GetProperty("Currency").GetString(); value = (T)(object)new Price(priceValue, priceCurrency); return(true); } if (typeof(T) == typeof(DateTime)) { string rawDateTime = element.GetString(); if (DateTime.TryParse(rawDateTime, out DateTime dateTime)) { value = (T)(object)dateTime; return(true); } else { log.Warning($"Get: Key: '{key}' not parseable to datetime from value '{rawDateTime}'."); value = default(T); return(false); } } } log.Debug($"Get: Key: '{key}' NOT FOUND. Storage: '{JsonSerializer.Serialize(storage)}'."); value = default(T); return(false); }