I have c# webapi on .net 6.0. And I am getting postdata from client into param_class into _input. the class is like following:
public class param_class
{
public string? name { get; set; }
public object? value { get; set; }
}
client sends data as json string like following:
{
"name": "lotnum",
"value": 143
}
in webapi, when I get value field throws error JsonElement cannot convert to Int.
var v = (int)_input.value;
how to convert from JsonElement to other types in webapi of .net 6.0?
Change
valuetype tointand default deserialization will handle this for you.What is actually happening right now is when you have an
objecttype for a property, it isJsonElementsince this is the type thatJSsends. But if you change it to the expected type, the default deserializer knows how to convert fromJsonElementto the specific type you are expecting. (sinceJsonElementitself sends what type it is)Of course, you have the option to post-cast it as follows:
I HARDLY suggest you not do it!