2024-07-19 20:02:28 +02:00
using System.Collections.Generic ;
2021-11-06 23:38:21 +01:00
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"/>.
2022-11-22 21:51:42 +01:00
/// Note that, using <see cref="SetData"/>, adding <see cref="JsonTypeSafeWrapper{T}"/> instances directly is also possible.
2021-11-06 23:38:21 +01:00
/// </summary>
2022-12-13 13:11:36 +01:00
#if NET7_0_OR_GREATER
2022-10-31 18:33:53 +01:00
[System.Diagnostics.CodeAnalysis.RequiresDynamicCode("The native code for instantiation of JsonTypeSafeWrapper instances might not be available at runtime.")]
2022-12-13 13:11:36 +01:00
#endif
2021-11-06 23:38:21 +01:00
public class JsonTypeSafeGenericDataHolder : IGenericDataHolder {
2022-09-14 21:17:43 +02:00
private static readonly string [ ] EmptyStrings = new string [ 0 ] ;
2022-11-22 20:09:12 +01:00
[JsonProperty]
2021-11-06 23:38:21 +01:00
private Dictionary < string , JsonTypeSafeWrapper > data ;
2022-11-27 12:34:07 +01:00
/// <inheritdoc />
public void SetData < T > ( string key , T data ) {
if ( EqualityComparer < T > . Default . Equals ( 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 > ( ) ;
2022-11-28 00:43:50 +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 />
2022-09-14 21:17:43 +02:00
public IEnumerable < string > GetDataKeys ( ) {
2021-11-06 23:38:21 +01:00
if ( this . data = = null )
2022-09-14 21:17:43 +02:00
return JsonTypeSafeGenericDataHolder . EmptyStrings ;
2021-11-06 23:38:21 +01:00
return this . data . Keys ;
}
}
2022-06-17 18:23:47 +02:00
}