Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET Core System.Text.Json JsonValueKind

I am facing an issue with JsonValueKind,which is I cannot access their values. I am working with Hyperpay for payment checkout.

I use the below method to make a request to their api and deserialize the response as follows:

enter image description here

In the home controller corresponding action method I am calling the request() method to get the result. Below is how the result look:

enter image description here

For example I am stuck with getting the value of code & description because they are stored in a JsonValueKind. Could you please help me deal with JsonValueKind to extract the values.

You help is much appreaciated.

like image 614
Ali Sultan Avatar asked Oct 29 '25 08:10

Ali Sultan


1 Answers

If you want to get the object value in result,here is a working demo like below:

public void Test()
{
    //the data here is the same as reader.ReadToEnd() in your project
    var data = GetRequest();

    //your result
    var responseData = JsonSerializer.Deserialize<Dictionary<string, dynamic>>(data);
    
    //change like below
    var d = JsonDocument.Parse(data);  //JsonDocument.Parse(reader.ReadToEnd())
    var result = d.RootElement.EnumerateObject();
    foreach (var r in result)
    {
        if (r.Value.ValueKind == JsonValueKind.String)
        {
            var stringValue = r.Value.GetString();
        }
        if (r.Value.ValueKind == JsonValueKind.Object)
        {
            var m = JsonSerializer.Deserialize<TestModel>(r.Value.GetRawText());
            var Code = m.code;
            var des = m.description;
        }
    }
       
}

Model:

public class TestModel
{
    public string code { get; set; }
    public string description { get; set; }
}

Result: enter image description here

The simple way is to create a ViewModel for the result like below:

public class ViewModel
{
    public TestModel result { get; set; }
    public string buildNumber { get; set; }
}

Deserialize the json string and get value like below:

var responseData = JsonSerializer.Deserialize<ViewModel>(reader.ReadToEnd());
var code = responseData.result.code;
var des = responseData.result.description;
like image 133
Rena Avatar answered Oct 31 '25 00:10

Rena



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!