【问题标题】:ASP.NET Core System.Text.Json JsonValueKindASP.NET Core System.Text.Json JsonValueKind
【发布时间】:2020-08-20 16:14:46
【问题描述】:

我遇到了 JsonValueKind 的问题,即我无法访问它们的值。我正在使用 Hyperpay 进行付款结账。

我使用以下方法向他们的 api 发出请求并反序列化响应如下:

在home控制器对应的action方法中我调用request()方法得到结果。下面是结果的样子:

例如,我坚持获取代码和描述的值,因为它们存储在 JsonValueKind 中。请您帮我处理 JsonValueKind 以提取值。

非常感谢您的帮助。

【问题讨论】:

  • 嗨@Ali,我的回答对你有帮助吗?

标签: json asp.net-core json-deserialization


【解决方案1】:

如果你想在结果中获取对象值,这里有一个工作演示,如下所示:

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;
        }
    }
       
}

型号:

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

结果:

简单的方法是为结果创建一个 ViewModel,如下所示:

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

反序列化json字符串并获取如下值:

var responseData = JsonSerializer.Deserialize<ViewModel>(reader.ReadToEnd());
var code = responseData.result.code;
var des = responseData.result.description;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-01-25
    • 1970-01-01
    • 1970-01-01
    • 2020-12-13
    • 1970-01-01
    • 2021-09-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多