using System;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace Sandbox;
///
/// A simple class for storing and retrieving metadata values.
///
public class Metadata
{
private Dictionary Data { get; set; }
///
/// Deserialize metadata from a JSON string.
///
internal static Metadata Deserialize( string json )
{
var data = Json.Deserialize>( json );
return new Metadata( data );
}
///
/// Serialize the metadata to a JSON string.
///
internal string Serialize()
{
return JsonSerializer.Serialize( Data, Json.options );
}
internal Metadata( Dictionary data )
{
Data = new Dictionary( data, StringComparer.OrdinalIgnoreCase );
}
public Metadata()
{
Data = new( StringComparer.OrdinalIgnoreCase );
}
///
/// Set a value with the specified key.
///
public void SetValue( string key, object value )
{
Data[key] = value;
}
///
/// Try to get a value of the specified type.
///
public bool TryGetValue( string key, out T outValue )
{
outValue = default;
if ( !Data.TryGetValue( key, out var value ) )
return false;
if ( value is T t )
{
outValue = t;
return true;
}
if ( value is JsonElement je )
{
try
{
outValue = je.Deserialize( Json.options ) ?? default;
}
catch ( Exception )
{
return false;
}
}
return true;
}
///
/// Get the a value. If it's missing or the wrong type then use the default value.
///
public T GetValueOrDefault( string key, T defaultValue = default )
{
if ( !Data.TryGetValue( key, out var value ) )
return defaultValue;
if ( value is T t )
{
return t;
}
if ( value is JsonElement je )
{
try
{
return je.Deserialize( Json.options ) ?? defaultValue;
}
catch ( Exception )
{
return defaultValue;
}
}
return defaultValue;
}
}