Model to JsonElement

457 Views Asked by At

What is the best/quickest way to convert a Model to JsonElement?

Background: I have existing code for a Controller that passes JsonElement from the request body to a repository. Now I have another Controller that first needs to do some logic on the Model, then I want to pass this to the same repository as the first controller. The problem is I cannot seem to figure a way of converting the Model to JsonElement other than this:

[HttpPost]
public async Task<IActionResult> Insert([FromBody] MyModel model)
{
    //Amazing logic done to model remove as it is not needed
    var json = JsonSerializer.Serialize(model);
    using var doc = JsonDocument.Parse(json);
    var results = _repository.Insert(doc.RootElement);
    //Amazing logic parsing the results
}

This does work, just seems like way too many steps. If there is no other way then so be it.

2

There are 2 best solutions below

0
On BEST ANSWER

Outside of the controller you can use JsonSerializer which has SerializeToElement and SerializeToDocument methods:

var element = JsonSerializer.SerializeToElement(model);
var results = _repository.Insert(element);

For controller action you can just accept JsonElement/JsonDocument as a parameter:

[HttpPost]
public async Task<IActionResult> Insert([FromBody] JsoneElement model)
{
    var results = _repository.Insert(model);
    ...
}
0
On

I am not sure that my solution is better than yours, but I think it is worth a try.

You can get a raw json from a body (example here). Then, you can create a JsonElement from it without a need to serialize the model to json. You will need to deserialize the MyModel explicitly in your code, but it should be done anyway (and will be done either by you or by the model binding mechanism)