-1

I need otp value from the following dynamic otp json element I am recieving in Web API Controller. I have tried a lot of things but couldn't find.

This is how I receive in controller

enter image description here

Quick watch window

enter image description here

touseefkhan4pk
  • 473
  • 4
  • 26
  • Does this answer your question? [System.Text.Json.JsonElement ToObject workaround](https://stackoverflow.com/questions/58138793/system-text-json-jsonelement-toobject-workaround) – JHBonarius Jan 20 '23 at 09:06
  • 1
    You can use [`.GetProperty("otp")`](https://learn.microsoft.com/en-us/dotnet/api/system.text.json.jsonelement.getproperty) to access the internal element. That will return a new `JsonElement`, which is a string. So use `.GetString()` on that. But the better (=C# like) answer is [here](https://stackoverflow.com/a/59047063). You need to deserialize the `JsonElement` to a proxy class or a `Dictionary` (or `Dictionary` for this simple type). – JHBonarius Jan 20 '23 at 09:11

1 Answers1

1

As your Quick Watch shows:

When you use dynamic here, it won't be deserialized to an object with the properties in json, but will return a JsonElement.

You can use its methods to parse the json as you like. Meanwhile you can just receive it like [FromBody] JsonElement opt.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
yueyinqiu
  • 369
  • 1
  • 7
  • ah, of course. dumb of me. It should even be `[FromBody]string opt`, as `JsonElement` is not needed at all. – JHBonarius Jan 20 '23 at 10:46