gpt4 book ai didi

c# - 将 JSON 反序列化为 List 时出错

转载 作者:行者123 更新时间:2023-11-30 19:14:53 25 4
gpt4 key购买 nike

我想将此 json 反序列化为 Product 对象列表,但出现此错误:

Newtonsoft.Json.JsonSerializationException: Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[ShoppingList.Product]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly. To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object.

这是我的代码:

{
"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;
}

最佳答案

你的 Json 不是 List<Product> ,它是一个具有名为 records 的单个属性的对象 List<Product> .

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

public class RootObject
{
public List<Product> records { get; set; }
}

然后你像这样反序列化:

RootObject productsRoot = JsonConvert.DeserializeObject<RootObject>(content);

关于c# - 将 JSON 反序列化为 List<T> 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51865305/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com