[英]looping through JSON object at adding each record to list c#
I'm a bit new to c#, and I am trying to add all the records I return back from my web service and add them to their designated list.我对 c# 有点陌生,我正在尝试添加从 Web 服务返回的所有记录,并将它们添加到指定列表中。 My JSON looks something like this:我的 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","sDescription":"All Vegetables"},....]
}
Both Products and Categories are returning several 100 or 1000 products.产品和类别都返回了 100 或 1000 个产品。 SO far I have this to try and iterate through them and add them to their own list to then add both lists to Two local tables I have in my app called Product and Category.到目前为止,我已经尝试遍历它们并将它们添加到自己的列表中,然后将两个列表添加到我的应用程序中名为 Product 和 Category 的两个本地表中。
I am clearly doing something wrong because my current code is not working.我显然做错了什么,因为我当前的代码不起作用。 private List _product = new List();私人列表_产品=新列表(); private List _category = new List();私人列表_category = 新列表();
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)
}
}
My error is as follows Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: The best overloaded method match for 'System.Collections.Generic.List<Project.Models.Category>.Add(Project.Models.Category)' has some invalid arguments我的错误如下Microsoft.CSharp.RuntimeBinder.RuntimeBinderException:'System.Collections.Generic.List<Project.Models.Category>.Add(Project.Models.Category)' 的最佳重载方法匹配有一些无效参数
I checked out my Category Class and I think I have everything I need.我检查了我的类别类,我想我拥有我需要的一切。
public class Category
{
[PrimaryKey]
public int iCatID { get; set; }
public string sDescription { get; set; }
}
I don't get what it says invalid arguments.我不明白它所说的无效参数。 I get this for both category and product.我为类别和产品都得到了这个。 Any recommendations?有什么建议吗? EDIT: I have also tried it this using the RootObject, I just didn't know how to access the product and category lists from there:编辑:我也尝试过使用 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; }
}
I added two more things to both the JSON and RootObject.我向 JSON 和 RootObject 添加了另外两个东西。
you need to deserialize your data into a concrete type您需要将数据反序列化为具体类型
var data = JsonConvert.DeserializeObject<RootObject>(content);
foreach(var obj in data.ProductItems)
{
_product.Add(obj);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.