【发布时间】:2021-01-27 05:32:50
【问题描述】:
我正在尝试使用 rawg api 并从他们的 api 获取游戏,我创建了游戏实体类来解析数据
//game entity
public class Game
{
public int Id { get; set; }
public string Slug { get; set; }
public string Name { get; set; }
public string Released { get; set; }
public string Background_Image { get; set; }
public int Rating { get; set; }
public int Playtime { get; set; }
}
现在我需要从 api 获取游戏,我做了这个方法
public static async Task<List<Game>> ApiRawgGamesRequest()
{
var gamesList = new List<Game>();
for (int i = 1; i < 250; i++)
{
using (var msg = new HttpRequestMessage(HttpMethod.Get, new Uri($"https://api.rawg.io/api/games?page_size=40&page={i}")))
using (var response = await _client.SendAsync(msg))
{
response.EnsureSuccessStatusCode();
var gamesResponse = await response.Content.ReadAsAsync<Game[]>();
gamesList.AddRange(gamesResponse);
}
}
return gamesList;
}
我试图不一次添加所有游戏,所以我使用 for 循环不断地将游戏添加到列表中,以潜在地减轻压力。 但我得到一个错误
// error
Unhandled exception. System.AggregateException: One or more errors occurred. (Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'Domain.Game[]' because the t
ype 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 'count', line 1, position 9.)
来自 rawg api 的响应看起来像这样——结果部分是我试图收集的游戏数据
// api response
{
"count": 454988,
"next": "https://api.rawg.io/api/games?page=2&page_size=40",
"previous": null,
"results": [
{
"id": 3498,
"slug": "grand-theft-auto-v",
"name": "Grand Theft Auto V",
"released": "2013-09-17",
"tba": false,
"background_image": "https://media.rawg.io/media/games/84d/84da2ac3fdfc6507807a1808595afb12.jpg",
"rating": 4.48,
},
{
"id": 4200,
"slug": "portal-2",
"name": "Portal 2",
"released": "2011-04-18",
"tba": false,
"background_image": "https://media.rawg.io/media/games/328/3283617cb7d75d67257fc58339188742.jpg",
"rating": 4.62
}
]
}
有没有更好的方法来做到这一点?
【问题讨论】:
-
您确定此链接是 API 调用吗? (api.rawg.io/api/games?page_size=40&page=)
-
哦,是的,我忘了它是从 0 开始的,但即使我从 1 开始,我仍然会收到错误
标签: c# asp.net-core asp.net-web-api .net-core