我正在尝试调用一个api端点,该端点包含基于查询字符串的图像列表。因此,如果我要查找猫的照片,则可以传递该参数和api键,然后可以获取猫的照片。
我正在使用的api端点是: https://pixabay.com/api/
以下是该api的示例响应:
{
"total": 4692,
"totalHits": 500,
"hits": [
{
"id": 195893,
"pageURL": "https://pixabay.com/en/blossom-bloom-flower-195893/",
"type": "photo",
"tags": "blossom, bloom, flower",
"previewURL": "https://cdn.pixabay.com/photo/2013/10/15/09/12/flower-195893_150.jpg"
"previewWidth": 150,
"previewHeight": 84,
"webformatURL": "https://pixabay.com/get/35bbf209e13e39d2_640.jpg",
"webformatWidth": 640,
"webformatHeight": 360,
"largeImageURL": "https://pixabay.com/get/ed6a99fd0a76647_1280.jpg",
"fullHDURL": "https://pixabay.com/get/ed6a9369fd0a76647_1920.jpg",
"imageURL": "https://pixabay.com/get/ed6a9364a9fd0a76647.jpg",
"imageWidth": 4000,
"imageHeight": 2250,
"imageSize": 4731420,
"views": 7671,
"downloads": 6439,
"favorites": 1,
"likes": 5,
"comments": 2,
"user_id": 48777,
"user": "Josch13",
"userImageURL": "https://cdn.pixabay.com/user/2013/11/05/02-10-23-764_250x250.jpg",
},
{
"id": 73424,
...
},
...
]
}
这是我设置的api调用:
public async Task<List<Image>> GetCatImages()
{
string query = "cats";
return await Get<List<Image>>(_baseUrl + $"?key={apiKey}&q={query}&image_type=photo");
}
这是get方法:
protected async Task<T> Get<T>(string url)
{
using (HttpClient client = GetClient())
{
try
{
var response = await client.GetAsync(url);
var obj = JsonConvert.DeserializeObject<T>(
await response.Content.ReadAsStringAsync());
return obj;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
}
我遇到的主要问题是:我认为get方法已损坏。我无法正确反序列化JSON,并且不确定上面的操作是错误的。设置obj(反序列化部分)后,我的代码中断。我究竟做错了什么?
以下是异常详细信息:
Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[Models.Image]' 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<T>) 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.
Path 'totalHits', line 1, position 13.
答案 0 :(得分:3)
您正尝试将Json反序列化为List<Image>
,但您的Json实际上只是一个Image
对象(内部包含一个列表)。
将您的呼叫更改为以下呼叫:
await Get<Image>(yourUri)