如何将JSON反序列化为List <T>?

Met*_*noy 2 c# json json.net

我想将此json反序列化为List of Product对象,但是我收到此错误:

Newtonsoft.Json.JsonSerializationException:无法将当前JSON对象(例如{"name":"value"})反序列化为类型'System.Collections.Generic.List`1 [ShoppingList.Product]',因为该类型需要JSON数组(例如[1,2,3])正确反序列化.要修复此错误,请将JSON更改为JSON数组(例如[1,2,3])或更改反序列化类型,使其成为普通的.NET类型(例如,不是像整数这样的基本类型,而不是类似的集合类型可以从JSON对象反序列化的数组或List.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;
    }
Run Code Online (Sandbox Code Playgroud)

mac*_*ura 9

您的JSON是不是一个List<Product>,它的使用称为单一属性的对象records一个List<Product>.

所以你的实际C#模型是这样的:

public class RootObject
{
    public List<Product> records { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

你反序列化如下:

RootObject productsRoot = JsonConvert.DeserializeObject<RootObject>(content);
Run Code Online (Sandbox Code Playgroud)