如何迭代包含两个类列表的类? - RestSharp

时间:2015-08-30 23:40:10

标签: c# json deserialization restsharp

这是我的数据:

{
  "-JxsJFiGBqQz1KQmmR0i" : {
    "bizcardData" : {
      "company" : "Tesla",
      "designation" : "Developer",
      "email" : "phani@tesla.com",
      "name" : "Phani",
      "phone" : "5135921241"
    },
    "transData" : {
      "date" : "15-08-29",
      "location" : "39.1395996,-84.5295417",
      "tag" : "sender",
      "time" : "03:17:00"
    }
  },
  "-JxsJKnJIVTFQWE1aSOr" : {
    "bizcardData" : {
      "company" : "Spotify",
      "designation" : "Designer",
      "email" : "komarapa@spotify.com",
      "name" : "Phani Komaravolu",
      "phone" : "5135921241"
    },
    "transData" : {
      "date" : "15-08-29",
      "location" : "39.1395996,-84.5295417",
      "tag" : "sender",
      "time" : "03:17:21"
    }
  }
}

这是我的交易类:

public class Transactions
    {
            public BizcardData bizcardData { get; set; }
            public TransData transData { get; set; }
    }

public class BizcardData
{
    public string company { get; set; }
    public string designation { get; set; }
    public string email { get; set; }
    public string name { get; set; }
    public string phone { get; set; }
}

public class TransData
{
    public string date { get; set; }
    public string location { get; set; }
    public string tag { get; set; }
    public string time { get; set; }
}

我使用RestSharp进行反序列化:

var resultList = SimpleJson.DeserializeObject<Dictionary<string, Transactions>>(content);

            Console.WriteLine ("Deserialized resultList"+resultList);

            foreach(var item in resultList)
            {
                var key = item.Key;
                var value = item.Value;

            /*  foreach(Transactions go in item.Value)
                {
                    var bizcardData = go.bizcardData;
                    var transData = go.transData;

                }*/
            }

此代码将Key作为唯一值,将值作为Transaction。

如果我尝试迭代Transaction类,我收到一个错误说,必须实现IEnumerable。如何迭代事务类并获取值。

谢谢!

2 个答案:

答案 0 :(得分:0)

它不是两个类的列表。您所拥有的是Object类型{{1>}(),其中包含两个属性:

Transactions

答案 1 :(得分:0)

如果你不关心这些键,你可以迭代字典的值(Transactions)。

var resultList = SimpleJson.DeserializeObject<Dictionary<string, Transactions>>(content);

Console.WriteLine ("Deserialized resultList"+resultList);

foreach(var transaction in resultList.Values)
{
     var bizcardData = transaction.bizcardData;
     var transData = transaction.transData;
}

如果你关心键,只需摆脱你的第二个循环。

var resultList = SimpleJson.DeserializeObject<Dictionary<string, Transactions>>(content);

Console.WriteLine ("Deserialized resultList"+resultList);

foreach(var pair in resultList)
{
     var key = pair.Key;
     var transaction = pair.Value;
     var bizcardData = transaction.bizcardData;
     var transData = transaction.transData;
}