Squidgy
Squidgy
CC#
Created by Owez on 6/29/2023 in #help
Implementing JsonConverter to simplify Ser/De
This doesn't necessarily answer your question since you specifically asked about JsonConverter.. But one way to go about it is to use a Dictionary, e.g. implement a method like this in your Snapshot class:
public string SerializeToJson(Snapshot<T> snapshot)
{
var dictionary = new Dictionary<DateTime, T>
{
{ snapshot.Taken, snapshot.Data }
};

return JsonSerializer.Serialize(dictionary);
}
public string SerializeToJson(Snapshot<T> snapshot)
{
var dictionary = new Dictionary<DateTime, T>
{
{ snapshot.Taken, snapshot.Data }
};

return JsonSerializer.Serialize(dictionary);
}
Then you can call it like this:
var snapshot = new Snapshot<string>
{
Taken = new DateTime(2022, 06, 21),
Data = "this is some data here!!"
};

var json = snapshot.SerializeToJson(snapshot);
// {"2022-06-21T00:00:00":"this is some data here!!"}
var snapshot = new Snapshot<string>
{
Taken = new DateTime(2022, 06, 21),
Data = "this is some data here!!"
};

var json = snapshot.SerializeToJson(snapshot);
// {"2022-06-21T00:00:00":"this is some data here!!"}
Perhaps the same approach could be used inside your SnapshotConverter
4 replies