【问题标题】:JSON Adding List<class> to class xxxJSON 将 List<class> 添加到类 xxx
【发布时间】:2017-08-27 12:12:01
【问题描述】:

我正在尝试将数据添加到列表中,然后将其添加到另一个列表中`{

{
    "name": "0001",
    "id": "donut",
    "total": {
        "price": [{
                "date": "1001",
                "type": "Regular"
            },
            {
                "id": "1002",
                "type": "Chocolate"
            },
            {
                "id": "1003",
                "type": "Blueberry"
            },
            {
                "id": "1004",
                "type": "Devil's Food"
            }
        ]
    }
}

这就是输出 Json 的样子。以下是我的一些代码:

public class TotalPrice
{
  public string date { get; set; }
  public string price { get; set; }
}

public class TotalPrices
{
  public List<TotalPrice> Price { get; set; }
}

public class AgencyCompare
{
  public string name { get; set; }
  public string id { get; set; }
  public TotalPrices total { get; set; }
}

for (int j = 0; j < dtFIT.Rows.Count; j++)
{
  var xTrans = new AgencyCompare();
  var xxx = new List<TotalPrice>();
  Debug.WriteLine("Start xTrans.ID");
  xTrans.id = id[j];
  Debug.WriteLine("End xTrans.ID");
  Debug.WriteLine("Start xTrans.name");
  xTrans.name = name[j];
  Debug.WriteLine("End xTrans.name");
  if (rowCount[j] > 0)
  {
    Debug.WriteLine("ROWCOUNT > 0");
    for (int z = 0; z < rowCount[j]; z++)
    {
      Debug.WriteLine("Start xTrans2");
      var xTrans2 = new TotalPrice();
      Debug.WriteLine("Start xTrans2.date");
      xTrans2.date = AtDay[j, z];
      Debug.WriteLine("End xTrans2.date");
      Debug.WriteLine("Start xTrans2.price");
      xTrans2.price = TotalPrice[j, z];
      Debug.WriteLine("End xTrans2.price");
      xxx.Add(xTrans2);
      Debug.WriteLine("xTrans.total.Price.Add(xTrans2)");
    }
    xTrans.total.Price.AddRange(xxx);
  }
  else
  {
    //
  }
  //xTrans.date = AtDay[j];
  //xTrans.total = TotalPrice[j];
  Debug.WriteLine("xAryTransCheckIn.Add(xTrans)");
  xAryTransCheckIn.Add(xTrans);
}
return xAryTransCheckIn;

调试时的错误:

启动 xTrans2

启动 xTrans2.date

结束 xTrans2.date

启动 xTrans2.price

结束 xTrans2.price

xTrans.total.Price.Add(xTrans2)

启动 xTrans2

启动 xTrans2.date

结束 xTrans2.date

启动 xTrans2.price

结束 xTrans2.price

xTrans.total.Price.Add(xTrans2)

启动 xTrans2

启动 xTrans2.date

结束 xTrans2.date

启动 xTrans2.price

结束 xTrans2.price

xTrans.total.Price.Add(xTrans2)

抛出异常:Webrestful.dll 中的“System.NullReferenceException”`

当我调用 xTrans.total.Price.AddRange(xxx); 时抛出异常,我不确定我是否设置了正确的类格式,或者我尝试添加列表时出错。

【问题讨论】:

  • 你调试的时候是totalnull?还是Price

标签: c# json list arraylist


【解决方案1】:

您缺少xTrans.total =new TotalPrices()xTrans.total.Price = new List&lt;TotalPrice&gt;()

【讨论】:

    猜你喜欢
    • 2016-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-21
    • 1970-01-01
    • 2018-01-27
    • 2020-04-24
    相关资源
    最近更新 更多