模型到JSONELEMENT
将模型转换为JSONELEMENT的最佳/最快方法是什么?
背景: 我有一个控制器的现有代码,该控制器将jsonelement从请求主体传递到存储库。现在,我有另一个控制器,首先需要在模型上执行一些逻辑,然后我想将其传递给与第一个控制器相同的存储库。问题是我似乎无法找到一种将模型转换为JSONELEMENT的方式:
[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
}
这确实有效,似乎太多的步骤。如果没有其他方法,那就就是这样。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在控制器之外,您可以使用
jsonserializer
具有 和 方法:对于控制器操作,您可以接受
jsonelement
/jsondocument
作为参数:Outside of the controller you can use
JsonSerializer
which hasSerializeToElement
andSerializeToDocument
methods:For controller action you can just accept
JsonElement
/JsonDocument
as a parameter:我不确定我的解决方案是否比您的解决方案更好,但我认为值得一试。
您可以从身体中获得RAW JSON(例如在这里)。然后,您可以从中创建一个JSONELEMENT,而无需将模型序列到JSON。您将需要在代码中明确化
myModel
,但无论如何都应该完成(并且将由您或模型绑定机制完成)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)