Cookies
Cookies

Reputation: 127

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. My JSON looks something like this:

{
  
 "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. 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.

I am clearly doing something wrong because my current code is not working. private List _product = new List(); private 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)
              }
}

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

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:

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.

Upvotes: 0

Views: 352

Answers (1)

Jason
Jason

Reputation: 89092

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

Upvotes: 1

Related Questions