【问题标题】:how can to parse in c# JSON with dynamic key using JSON.NET or any other package如何使用 JSON.NET 或任何其他包使用动态密钥解析 c# JSON
【发布时间】:2019-08-06 04:51:38
【问题描述】:

大家好,我有问题如何使用这些数据解析 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; }
}

【问题讨论】:

  • 你对这个Datas data { get; set; }有什么问题,How can i parse it是什么意思?
  • 我的问题是如何将 data_0、data_1 放在一个类中,因为您可以看到 JSON 响应具有增量值,我可能希望将它放在一个类中
  • 你可以动态数据类型而不是上面这个json的类。
  • @Mano 你能举例说明你的意思吗?

标签: c# asp.net json asp.net-core jsonparser


【解决方案1】:

只需稍微更改您的 Stat 类:

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之类的东西

【讨论】:

    【解决方案2】:

    Dictionary&lt;string, Datas&gt; 用于Stat 类中的属性Customer

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

    输出:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-03-10
      • 2019-02-13
      • 1970-01-01
      • 2020-08-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多