[英]Validating Json outputs in c#
我正在嘗試通過url驗證json的輸出,所以這是一個輸出的json
{
"response": {
"players": [
{
"steamid": "76561197960435530",
"communityvisibilitystate": 3,
"profilestate": 1,
"personaname": "Robin",
"lastlogoff": 1460271265,
"profileurl": "http://steamcommunity.com/id/robinwalker/",
"avatar": "https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/f1/f1dd60a188883caf82d0cbfccfe6aba0af1732d4.jpg",
"avatarmedium": "https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/f1/f1dd60a188883caf82d0cbfccfe6aba0af1732d4_medium.jpg",
"avatarfull": "https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/f1/f1dd60a188883caf82d0cbfccfe6aba0af1732d4_full.jpg",
"personastate": 0,
"realname": "Robin Walker",
"primaryclanid": "103582791429521412",
"timecreated": 1063407589,
"personastateflags": 0,
"loccountrycode": "US",
"locstatecode": "WA",
"loccityid": 3961
}
]
}
}
這是一個缺少對象,但仍然有一個輸出所以我的程序拋出一個錯誤,因為它找不到我正在嘗試使用的json輸出。
{
"response": {
"players": [
]
}
}
這是我正在使用的代碼。 我從用戶那里獲得了SteamID,如果它不正確,它會在播放器數組中輸出沒有對象的json,但問題是如果我的程序找不到json對象o [“personastate”]它會拋出一個錯誤。 想知道如何反擊這個? 任何幫助贊賞
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace JSONTest
{
class Program
{
static void Main(string[] args)
{
string SteamKey = "APIKEY";
Console.WriteLine("Give SteamID Please");
string SteamID = Console.ReadLine();
WebClient c = new WebClient();
var data = c.DownloadString("http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/" + "?key=" + SteamKey + "&steamids=" + SteamID);
//Console.WriteLine(data);
JObject o = JObject.Parse(data);
int PrivacyLevel = (int)o["response"]["players"][0]["communityvisibilitystate"];
string username = (string)o["response"]["players"][0]["personaname"];
string ProUrl = (string)o["response"]["players"][0]["profileurl"];
if (PrivacyLevel == 3)
{
Console.WriteLine("Profile Status: Public");
}
else if (PrivacyLevel == 1)
{
Console.WriteLine("Profile Status: Private");
}
else
{
Console.WriteLine("You have typed the Steam ID Incorrectly");
}
Console.ReadLine(); // Don't remove you idiot
}
}
}
您可以檢查["players"]
數組中是否有任何對象(我沒有測試過這段代碼):
JObject o = JObject.Parse(data);
JArray players = (JArray)o["response"]["players"];
if(players.Count > 0){
int PrivacyLevel = (int)players[0]["communityvisibilitystate"];
string username = (string)players[0]["personaname"];
string ProUrl = (string)players[0]["profileurl"];
if (PrivacyLevel == 3)
{
Console.WriteLine("Profile Status: Public");
}
else if (PrivacyLevel == 1)
{
Console.WriteLine("Profile Status: Private");
}
}
else
{
Console.WriteLine("You have typed the Steam ID Incorrectly");
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.