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:
In the home controller corresponding action method I am calling the request()
method to get the result. Below is how the result look:
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.
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; }
}
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;