首页 > 解决方案 > 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;
        }    
}

标签: c#json

解决方案


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
}

推荐阅读