C#-如何处理JSON.NET中JSON URL中的404错误

时间:2018-10-22 11:17:00

标签: c# json

上下文

我正在开发一个小型控制台应用程序,该应用程序允许输入英雄联盟中任何EUW玩家的用户名,并且应该尝试观看他们的游戏。

问题

我的问题是,我真的不知道如何处理从Riot API接收到的JSON文件为空并给我404错误的情况。

代码

Program.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之外访问变量 summoner 时,如何根据第一个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;
        }    
}

1 个答案:

答案 0 :(得分:0)

尝试捕获不是这里的解决方法

在访问对象空值之前先检查对象空值

Ex-

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
}