Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a class instance to JsonDocument?

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))
like image 910
pbn Avatar asked Apr 02 '20 10:04

pbn


1 Answers

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 usings.

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.

like image 117
Fildor Avatar answered Nov 10 '22 00:11

Fildor