首页 > 解决方案 > 如何在 Blazor WASM 中将 JSON 动态 KeyValuePair 解析为 C# 模型

问题描述

我想解析对 C# 模型的 JSON 动态 KeyValuePair 响应,但出现错误。我正在使用 Blazor webassembly(最新版本)构建应用程序。我很确定我在 JSON 反序列化中犯了一个愚蠢的错误。你能纠正我吗?

我从 API 得到以下 JSON 响应:

{
    "message": "Success",
    "data": {
        "stores": {
            "": "Select Store",
            "21": "Indore store",
            "33": "test POS2",
            "34": "test POS4",
            "37": "test store 11",
            "36": "test store09",
            "59": "test store26"
        },
        "storeId": "21",
        "businessId": "1"
    }
}

并尝试像这样解析响应:

public async Task GetSetFilters()
{
    SetApiHeaders();
    var response = await Http.GetAsync("/pwa/v1/transaction-filters");
    TransactionFiltersModel content = await response.Content.ReadFromJsonAsync<TransactionFiltersModel>();
}

我的 TransactionFiltersModel 是:

public class TransactionFiltersModel
{
    public string message { get; set; }
    public TransactionFiltersData data { get; set; }
}

public class TransactionFiltersData
{
    public string storeId { get; set; }
    public int businessId { get; set; }

    public List<KeyValuePair<string, string>> stores { get; set; }
}

得到错误:

未处理的异常呈现组件:无法将 JSON 值转换为 System.Collections.Generic.List 1[System.Collections.Generic.KeyValuePair2[System.String,System.String]]。路径:$.data.stores | 行号:1 | BytePositionInLine:43。 System.Text.Json.JsonException:JSON 值无法转换为 System.Collections.Generic.List 1[System.Collections.Generic.KeyValuePair2[System.String,System.String]]。路径:$.data.stores | 行号:1 | BytePositionInLine: 43. 在 System.Text.Json.ThrowHelper.ThrowJsonException_DeserializeUnableToConvertValue (System.Type propertyType) <0x3070550 + 0x00032> in :0 .....

标签: c#jsonblazorblazor-client-sideblazor-webassembly

解决方案


推荐阅读