I'm serializing/deserializing a dictionary<string,object>, but when I deserialize, instead of the values being object
s, they are JsonElement
s.
I have a unit test that demonstrates the problem. How can I deserialize these values to object
s? Can anyone help? Do I have to write a custom converter?
[Test]
public void SerializationTest()
{
var coll = new PreferenceCollection();
coll.Set("email", "test@test.com");
coll.Set("age", 32);
coll.Set("dob", new DateOnly(1991, 2, 14));
var json = JsonSerializer.Serialize(coll);
Assert.NotNull(json);
var clone = JsonSerializer.Deserialize<PreferenceCollection>(json);
Assert.NotNull(clone);
Assert.IsNotEmpty(clone!.Values);
foreach (var kvp in clone.Values)
{
Assert.That(kvp.Value is not null);
// Test fails here because kvp.Value is JsonElement.
Assert.That(kvp.Value!.Equals(coll.Values[kvp.Key]));
}
}
using System.Text.Json.Serialization;
namespace MyCompany.Preferences;
public class PreferenceCollection
{
public PreferenceCollection()
{
Values = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
}
[JsonExtensionData] public IDictionary<string, object> Values { get; set; }
public object Get(string key)
{
if (Values.TryGetValue(key, out object value))
{
return value;
}
return null;
}
public T Get<T>(string key)
{
if (Values.TryGetValue(key, out var value))
{
return (T)value;
}
return default;
}
public void Set(string key, object value)
{
if (value == null)
{
Remove(key);
}
else
{
if (!Values.TryAdd(key, value))
{
Values[key] = value;
}
}
}
public void Remove(string key) => Values.Remove(key);
public void Clear() => Values.Clear();
}