简体   繁体   中英

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

Hi guys i am having problem how can i parse JSON with this data because as you can see below the data_0 key is incrementing i am having confusion how can i parse it using my models

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

this is my model

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

Use Dictionary<string, Datas> for property Customer in Stat class,

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

Usage:

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

Output:

在此处输入图片说明

Just change your Stat class a little:

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

Then you can use something like stat.Customer["data_0"].email

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM