在C#中遍历Steam API JSON数据,计算总游戏时长
计算Steam用户总游玩时长的C#实现
你可以通过遍历games数组中的每个游戏对象,提取playtime_forever字段并累加求和,完成需求。以下是修改后的完整代码:
public const string APIKey = ProtectedAPIKey.APIKey; public const string SteamGamesAPILink = $"https://api.steampowered.com/IPlayerService/GetOwnedGames/v1?key={APIKey}&steamid=76561198871868188"; public const string SteamLevelAPILink = $"https://api.steampowered.com/IPlayerService/GetSteamLevel/v1?key={APIKey}&steamid=76561198871868188"; static WebClient wc = new(); public static void Main() { byte[] SteamGamesAPIResponse = wc.DownloadData(SteamGamesAPILink); byte[] SteamLevelAPIResponse = wc.DownloadData(SteamLevelAPILink); string SteamLevelAPIResponseString = Encoding.Default.GetString(SteamLevelAPIResponse); string SteamGamesAPIResponseString = Encoding.Default.GetString(SteamGamesAPIResponse); var levelRoot = JToken.Parse(SteamLevelAPIResponseString); var gamesRoot = JToken.Parse(SteamGamesAPIResponseString); #pragma warning disable CS8604 var games = gamesRoot .SelectToken("response") .SelectToken("games"); #pragma warning restore CS8604 // 计算总游玩时长(分钟) int totalPlaytimeMinutes = 0; if (games != null && games.Type == JTokenType.Array) { foreach (var game in games) { int playtime = game.SelectToken("playtime_forever")?.Value<int>() ?? 0; totalPlaytimeMinutes += playtime; } } // 转换为小时(可选,提升可读性) double totalPlaytimeHours = Math.Round(totalPlaytimeMinutes / 60.0, 2); var level = levelRoot .SelectToken("response") .SelectToken("player_level"); Console.ForegroundColor = ConsoleColor.Blue; Console.WriteLine($"Player level: {level}"); Console.WriteLine($"Total playtime (minutes): {totalPlaytimeMinutes}"); Console.WriteLine($"Total playtime (hours): {totalPlaytimeHours}"); }
关键逻辑说明:
- 先校验
games的有效性,确保它是数组类型,避免空引用或类型错误 - 遍历每个游戏对象,用
SelectToken提取playtime_forever字段,通过?? 0处理字段缺失的情况,保证代码稳定性 - 累加所有游戏的时长得到总分钟数,额外转换为小时数可以让输出更直观
- 最后将总时长结果输出到控制台
内容的提问来源于stack exchange,提问作者rudynakodach
相关产品推荐
相关产品推荐

