2

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?

2 Answers 2

8

Change value type to int and default deserialization will handle this for you.

What is actually happening right now is when you have an object type for a property, it is JsonElement since this is the type that JS sends. But if you change it to the expected type, the default deserializer knows how to convert from JsonElement to the specific type you are expecting. (since JsonElement itself sends what type it is)

Of course, you have the option to post-cast it as follows:

var v = ((JsonElement)_input.value).GetInt32();

I HARDLY suggest you not do it!

Sign up to request clarification or add additional context in comments.

Comments

1

I tend to override the class and then add some functions to get back the various types of value:

public class param_class
{
    public string? Name { get; set; }
    public object? Value { get; set; }

    public int GetInt() => Value is int value ? value : Value is JsonElement jsonElement ? jsonElement.GetInt32() : 0;
    public double GetDouble() => Value is double value ? value : Value is JsonElement jsonElement ? jsonElement.GetDouble() : 0;
    public bool GetBoolean() => Value is bool value ? value : Value is JsonElement jsonElement ? jsonElement.GetBoolean() : false;
    public string? GetString() => Value is string value ? value : Value is JsonElement jsonElement ? jsonElement.GetString() : null;

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.