2021-11-06 23:38:21 +01:00
using System ;
using System.Collections.Generic ;
using System.Runtime.Serialization ;
using MLEM.Misc ;
using Newtonsoft.Json ;
namespace MLEM.Data.Json {
/// <summary>
/// An <see cref="IGenericDataHolder"/> represents an object that can hold generic key-value based data.
/// This class uses <see cref="JsonTypeSafeWrapper"/> for each object stored to ensure that objects with a custom <see cref="JsonConverter"/> get deserialized as an instance of their original type if <see cref="JsonSerializer.TypeNameHandling"/> is not set to <see cref="TypeNameHandling.None"/>.
/// </summary>
[DataContract]
public class JsonTypeSafeGenericDataHolder : IGenericDataHolder {
[DataMember(EmitDefaultValue = false)]
private Dictionary < string , JsonTypeSafeWrapper > data ;
/// <inheritdoc />
2021-11-07 00:23:48 +01:00
public void SetData ( string key , object data ) {
if ( data = = default ) {
2021-11-06 23:38:21 +01:00
if ( this . data ! = null )
this . data . Remove ( key ) ;
} else {
if ( this . data = = null )
this . data = new Dictionary < string , JsonTypeSafeWrapper > ( ) ;
2021-11-07 00:23:48 +01:00
this . data [ key ] = JsonTypeSafeWrapper . Of ( data ) ;
2021-11-06 23:38:21 +01:00
}
}
/// <inheritdoc />
public T GetData < T > ( string key ) {
if ( this . data ! = null & & this . data . TryGetValue ( key , out var val ) )
2021-11-07 00:46:35 +01:00
return ( T ) val . Value ;
2021-11-06 23:38:21 +01:00
return default ;
}
/// <inheritdoc />
2021-11-07 00:46:35 +01:00
public IReadOnlyCollection < string > GetDataKeys ( ) {
2021-11-06 23:38:21 +01:00
if ( this . data = = null )
return Array . Empty < string > ( ) ;
return this . data . Keys ;
}
}
2022-06-17 18:23:47 +02:00
}