C# 中的数组 Json 反序列化问题
Array Json Deserialization Issues in C#
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());
代码 运行,当结果解析只传递对象名称时,反序列化问题来自 listtostring,在这种情况下,它只是说它是一个列表,而不是在尝试时将列表本身传递给 var list获取项目。
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; }
}
最初捕获的 Json 示例
{"count":2,"products":[{"name":"item","location":"storeroom","_id":"6219602068c9a900043fe844"},{"name":"item2","location":"storeroom","_id":"6219603768c9a900043fe850"}]}
你只需要反序列化一次
var json = await result.Content.ReadAsStringAsync();
var resp = JsonConvert.DeserializeObject<ProductResponse>(json);
resp
是一个 ProductResponse
对象,应该包含 products
属性 中的所有产品详细信息。您不需要单独反序列化产品
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());
代码 运行,当结果解析只传递对象名称时,反序列化问题来自 listtostring,在这种情况下,它只是说它是一个列表,而不是在尝试时将列表本身传递给 var list获取项目。
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; }
}
最初捕获的 Json 示例
{"count":2,"products":[{"name":"item","location":"storeroom","_id":"6219602068c9a900043fe844"},{"name":"item2","location":"storeroom","_id":"6219603768c9a900043fe850"}]}
你只需要反序列化一次
var json = await result.Content.ReadAsStringAsync();
var resp = JsonConvert.DeserializeObject<ProductResponse>(json);
resp
是一个 ProductResponse
对象,应该包含 products
属性 中的所有产品详细信息。您不需要单独反序列化产品