我想将这个json反序列化为一个Product对象的List,但是我遇到了这个错误:
Newtonsoft.Json.JsonSerializationException: 无法将当前JSON对象(例如{"name":"value"})反序列化为类型'System.Collections.Generic.List`1[ShoppingList.Product]',因为该类型需要一个JSON数组(例如[1,2,3])才能正确反序列化。 要解决此错误,请将JSON更改为JSON数组(例如[1,2,3]),或更改反序列化类型,使其成为.NET普通类型(例如不是像整数这样的基元类型,也不是像数组或List这样的集合类型),可以从JSON对象反序列化。也可以向该类型添加JsonObjectAttribute,以强制它从JSON对象反序列化。
这是我的代码:
Newtonsoft.Json.JsonSerializationException: 无法将当前JSON对象(例如{"name":"value"})反序列化为类型'System.Collections.Generic.List`1[ShoppingList.Product]',因为该类型需要一个JSON数组(例如[1,2,3])才能正确反序列化。 要解决此错误,请将JSON更改为JSON数组(例如[1,2,3]),或更改反序列化类型,使其成为.NET普通类型(例如不是像整数这样的基元类型,也不是像数组或List这样的集合类型),可以从JSON对象反序列化。也可以向该类型添加JsonObjectAttribute,以强制它从JSON对象反序列化。
这是我的代码:
{
"records": [
{
"id": "60",
"name": "Rolex Watch",
"description": "Luxury watch.",
"price": "25000",
"category_id": "1",
"category_name": "Fashion"
},
{
"id": "48",
"name": "Bristol Shoes",
"description": "Awesome shoes.",
"price": "999",
"category_id": "5",
"category_name": "Movies"
},
{
"id": "42",
"name": "Nike Shoes for Men",
"description": "Nike Shoes",
"price": "12999",
"category_id": "3",
"category_name": "Motors"
}
]
}
public class Product
{
public int id { get; set; }
public string name { get; set; }
public string description { get; set; }
public decimal price { get; set; }
public int category_id { get; set; }
public string category_name { get; set; }
}
public async Task<List<Product>> GetProductsAsync()
{
Products = new List<Product>();
var uri = new Uri("https://hostname/api/product/read.php");
try
{
var response = await client.GetAsync(uri);
if (response.IsSuccessStatusCode)
{
var content = await response.Content.ReadAsStringAsync();
Products = JsonConvert.DeserializeObject<List<Product>>(content);
}
}
catch (Exception )
{
throw;
}
return Products;
}