Let's say we have an entity class that looks like this:
public class SerializedEntity
{
public JsonDocument Payload { get; set; }
public SerializedEntity(JsonDocument payload)
{
Payload = payload;
}
}
According to npsql this generates a table with column payload
of type jsonb
for this class which is correct.
Now what I would like to do is take any class instance and store it as payload
in this table e.g.:
public class Pizza {
public string Name { get; set; }
public int Size { get; set; }
}
should then be possible to be retrieved as an object with following structure:
{Name: "name", Size: 10}
So I need something like this:
var pizza = new Pizza("Margharita", 10);
var se = new SerializedEntity(someConverter.method(pizza))
With System.Text.Json it's a little awkward but possible:
using System.Text.Json;
using System.Text.Json.Serialization;
var pizza = new Pizza("Margharita", 10);
var se = new SerializedEntity(JsonDocument.Parse(JsonSerializer.Serialize(pizza)));
It has been built-in to dotnet core since (I think) v3.0, so you do not need any additional 3rd party libs. Just don't forget the using
s.
There may be some tricks to get the parsing a little more efficient, though (using async API, perhaps or as Magnus suggests by serializing to binary using SerializeToUtf8Bytes
).
I haven't been able to find any approach that goes directly from T
or object
to JsonDocument
. And I cannot believe this is not possible somehow. Please leave a comment if you know how that works or add your answer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With