Hi would need some help / advice. I would need to build an endpoint which takes in an argument of key value pairs, specifically Dictionary<string,dynamic> as the values may dynamic. Below is a my code snippet:
[ApiController]
[Route("api/General/[controller]")]
public class TestController : Controller
{
private readonly ILogger<TestController> _logger;
public TestController(ILogger<TestController> logger)
{
_logger = (ILogger<TestController>)logger;
}
[HttpPost]
public async Task<IActionResult> OnPost([FromBody] Dictionary<string,dynamic> incomingData)
{
string item01Id = incomingData["item01Id"];
int item01Value = incomingData["item01Value"];
string item02Id = incomingData["item02Id"];
string item02Value = incomingData["item02Value"];
return Ok();
}
}
For the test I did a Post with a json body of:
{
"item01Id": "Item 01",
"item01Value": 133,
"item02Id": "Item 02",
"item02Value": "some value"
}
Seems it was unable to assign the the value into the various .net variables as the dynamic values were of type System.Text.Json.JsonElement as shown by the exception: Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: Cannot implicitly convert type 'System.Text.Json.JsonElement' to 'string'
I have found a way by using the JsonElement's ValueKind. But I was wondering if there is a way where by I can deserialize it into a .net type directly instead of a JsonElement.
Added for additional context: Locals
Thanks in Advance