Home > Software design >  Array Json Deserialization Issues in C#
Array Json Deserialization Issues in C#

Time:03-04

string uri = Application.Current.Properties["Uri"].ToString();
var client = new HttpClient();
var result = await client.GetAsync(uri   "/products");
var resultparsing = JsonConvert.DeserializeObject<ProductResponse>(await 
result.Content.ReadAsStringAsync());
var list = JsonConvert.DeserializeObject<List<Item>>(resultparsing.products.ToString());

The code running, Deserialization issue coming from listtostring when the resultparsing is passing just the object name which in this case it just saying it is a list and not passing the list itself to var list when it attempts to fetch the items.

public class Item
    {
        public string _id { get; set; }
        public string name { get; set; }
        public string location { get; set; }
    }
    public class ProductResponse
    {
        public string count { get; set; }
        public List<Item> products { get; set; }
    }

Examples of Json that is initially being captured

{"count":2,"products":[{"name":"item","location":"storeroom","_id":"6219602068c9a900043fe844"},{"name":"item2","location":"storeroom","_id":"6219603768c9a900043fe850"}]}

CodePudding user response:

you only need to deserialize once

var json = await result.Content.ReadAsStringAsync();
var resp = JsonConvert.DeserializeObject<ProductResponse>(json);

resp is a ProductResponse object that should contain all of the product detail in the products property. You do not need to deserialize products separately

  • Related