如何使用 JSON.NET 或任何其他包在 c# JSON 中使用动态密钥进行解析

how can to parse in c# JSON with dynamic key using JSON.NET or any other package

大家好,我有问题如何使用此数据解析 JSON 因为正如您在下面看到的 data_0 键正在递增 我很困惑如何使用我的模型解析它

{
"status": {
    "connection_status": "successful",
    "operation_status": "successful",
    "Customer": {
        "data_0": {
            "id": "123321",
            "FirstName": "testFirstname",
            "LastName": "testlastname"
        },
        "data_1": {
            "id": "321123",
            "FirstName": "testFirstname",
            "LastName": "testlastname",
        }
    }
}
}

这是我的模型

public class GetAccountBalanceResponseModel
{
    public Stat status { get; set; }
}

public class Stat
{
    public string connection_status { get; set; }
    public string operation_status { get; set; }
    public Custmer Customer { get; set; }
}

public class Custmer
{
    public Datas data { get; set; } -- i am having problem with this one 
}

public class Datas
{
    public string id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string email { get; set; }
    public string accountBalance { get; set; }
}

稍微改变一下你的Statclass:

public class Stat
{
    public string connection_status { get; set; }
    public string operation_status { get; set; }
    public Dictionary<string, Datas> Customer { get; set; }
}

然后你可以使用像stat.Customer["data_0"].email

这样的东西

Stat class,

中对 属性 Customer 使用 Dictionary<string, Datas>
public class Stat
{
    public string connection_status { get; set; }
    public string operation_status { get; set; }
    public Dictionary<string, Datas> Customer { get; set; }
}

用法:

GetAccountBalanceResponseModel model = JsonConvert.DeserializeObject<GetAccountBalanceResponseModel>(json);    

foreach (var item in model.status.Customer)
{
    Console.WriteLine("Key: " + item.Key);
    Console.WriteLine("Id: " + item.Value.id);
    Console.WriteLine("FirstName: " + item.Value.FirstName);
    Console.WriteLine("LastName: " + item.Value.LastName);
    Console.WriteLine();
}

输出: