微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在将每个记录添加到列表C#中遍历JSON对象

如何解决在将每个记录添加到列表C#中遍历JSON对象

我对C#有点陌生,我试图将所有从Web服务返回的记录添加到自己的指定列表中。我的JSON看起来像这样:

{
  
 "errMsg":"","date":"2020-10-21 10:20:28","Category":
   [{"iCatID":"1","sDescription":"All},{"iCatID":"2","sDescription":"All vegetables"},....],"Product":
   [{"iProductID":"10","sDescription":"Apples},{"iProductID":"11",....]
}

“产品”和“类别”都返回了100或1000种产品。到目前为止,我可以尝试遍历它们并将它们添加到自己的列表中,然后将两个列表都添加到我在我的应用中拥有的两个本地表中,称为产品和类别。

我显然做错了,因为我当前的代码无法正常工作。 私有列表_product = new List(); 私人列表_category = new List();

public async void CreateLocalTables()    
{

try
          {
            _client.GetAsync("https://app.spcty.com/app/dbExport.PHP");
                var content = await response.Content.ReadAsstringAsync();
                dynamic data = JsonConvert.DeserializeObject(content);

             foreach (var obj in data.Product)
              {
                  Console.WriteLine(obj);
                  //does not work
                  _product.Add(obj)
              }
}

我的错误如下。 Microsoft.CSharp.RuntimeBinder.RuntimeBinderException:'System.Collections.Generic.List .Add(Project.Models.Category)'的最佳重载方法匹配有一些无效的参数

我检查了我的类别课程,我认为我有我需要的一切。

public class Category
    {

        [PrimaryKey]
        public int iCatID { get; set; }
        public string sDescription { get; set; }
}

我不明白它说的是无效参数。我对类别和产品都知道这一点。有什么建议吗? 编辑:我也尝试过使用RootObject,我只是不知道如何从那里访问产品和类别列表:

public class RootObject
{
    public  List<Category> CategoyItems { get; set; }

    public List<Product> ProductItems { get; set; }
    public string errMsg { get; set; }
    public string date { get; set; }            
}

我在JSON和RootObject中又添加了两点。

解决方法

您需要将数据反序列化为具体类型

var data = JsonConvert.DeserializeObject<RootObject>(content);

foreach(var obj in data.ProductItems)
{
  _product.Add(obj);
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。