c# - C# - 如何在 JSON.NET 中处理 JSON url 中的 404 错误
问题描述
语境
我正在开发一个小型控制台应用程序,该应用程序允许输入英雄联盟中任何 EUW 玩家的用户名,它应该尝试观看他们的游戏。
问题
我的问题是我真的不知道如何处理从 Riot API 收到的 JSON 文件为空并给我一个 404 错误。
编码
程序.cs
var json2 = new WebClient().DownloadString("https://euw1.api.riotgames.com/lol/summoner/v3/summoners/by-name/" + Username);
var summoner = JsonConvert.DeserializeObject<Summoner.RootObject>(json2);
var json = new WebClient().DownloadString("https://euw1.api.riotgames.com/lol/spectator/v3/active-games/by-summoner/" + summoner.id);
var model = JsonConvert.DeserializeObject<Model.RootObject>(json);
long gameid = model.gameId;
string encrypkey = model.observers.encryptionKey;
Spectate(gameid, encrypkey);
一个简单的 try-catch 就足够了吗?如果是这样,当我无法访问try-catch 之外的变量调用者时,我将如何正确地让它基于第一个 DeserializeObject 的成功尝试第二个 DeserializeObject?
EDIT2:我设法找到了一个很好的解决方案,它完全符合我的需要。
bool xd = true;
while (xd == true)
{
Console.Write("Enter username: ");
string Username = Console.ReadLine();
try
{
var json2 = new WebClient().DownloadString("https://euw1.api.riotgames.com/lol/summoner/v3/summoners/by-name/" + Username);
var summoner = JsonConvert.DeserializeObject<Summoner.RootObject>(json2);
var json = new WebClient().DownloadString("https://euw1.api.riotgames.com/lol/spectator/v3/active-games/by-summoner/" + summoner.id);
var model = JsonConvert.DeserializeObject<Model.RootObject>(json);
long gameid = model.gameId;
string encrypkey = model.observers?.encryptionKey;
Spectate(gameid, encrypkey);
xd = false;
}
catch (WebException ex)
{
if (ex.Status == WebExceptionStatus.ProtocolError && ex.Response != null)
{
var resp = (HttpWebResponse)ex.Response;
if (resp.StatusCode == HttpStatusCode.NotFound)
{
Console.WriteLine("This summoner does not exist or is not in a game");
Console.WriteLine("Please try again");
continue;
}
}
throw;
}
}
解决方案
Try Catch 不是这里的解决方案
在访问它们和那里的孩子之前检查对象空值
前任 -
var json2 = new WebClient().DownloadString("https://euw1.api.riotgames.com/lol/summoner/v3/summoners/by-name/" + Username);
var summoner = JsonConvert.DeserializeObject<Summoner.RootObject>(json2);
var json = new WebClient().DownloadString("https://euw1.api.riotgames.com/lol/spectator/v3/active-games/by-summoner/" + summoner.id);
var model = JsonConvert.DeserializeObject<Model.RootObject>(json);
if(model !=null){ // Checking for null
long gameid = model.gameId;
string encrypkey = model.observers?.encryptionKey; // Checking for null
}
推荐阅读
- reactjs - 在 React Native 中,如何在状态更改时更改导航选项?
- selenium - 黄瓜示例表未正确分隔
- ssms - 使用 SSMS 2014,如何生成高效的插入脚本?
- azure - 如何在 MS Azure 中创建应用程序以使用 aws lex 在 Outlook Office 365 中安排约会
- php - 如何找出 Wordpress 页面的一部分的来源?
- azure - 无法使用 FTPS 将文件从 Azure 发布管道复制到服务器
- typo3 - 我在哪里实现我的 TYPO3 扩展的设置 html?
- batch-file - 批处理脚本回显可用驱动器错误
- python - Django:当我在使用时导入 Django 模型或函数时,Celery 会抛出错误
- android - 在 Android 上膨胀布局 XML