WP8解析JSON格式(使用Newtonsoft.Json包)
DOTA2 WebAPI請求返回的格式有兩種,一種是XML,一種是JSON,默認是返回JSON格式。
這里舉一個簡單的解析JSON格式的例子(更多JSON操作):
{
"response": {
"players": [
{
"steamid": "76561198092319753",
"communityvisibilitystate": 1,
"profilestate": 1,
"personaname": "偶買噶、Scohura",
"lastlogoff": 1396240726,
"profileurl": "http://steamcommunity.com/profiles/76561198092319753/",
"avatar": "http://media.steampowered.com/steamcommunity/public/images/avatars/f9/f90a468b223389164861722c599318216b388f18.jpg",
"avatarmedium": "http://media.steampowered.com/steamcommunity/public/images/avatars/f9/f90a468b223389164861722c599318216b388f18_medium.jpg",
"avatarfull": "http://media.steampowered.com/steamcommunity/public/images/avatars/f9/f90a468b223389164861722c599318216b388f18_full.jpg",
"personastate": 0
}
]
}
}
解析代碼如下,輸入Stream流轉為String就是上面的文本
private void praseJSON(Stream json) { JObject user =JObject.Parse(new StreamReader(json).ReadToEnd()); JObject userdata = (JObject)((JArray)(user["response"]["players"]))[0]; //昵稱賦值、溢出部分使用省略號代替 username.Text = userdata["personaname"].ToString(); username.TextTrimming = TextTrimming.WordEllipsis; username.FontSize = (this.Height - 80) / 3; //狀態賦值 switch (userdata["personastate"].ToString()) { case "0": if (userdata["communityvisibilitystate"].ToString().Equals("1")) { statusText = "該用戶資料未公開"; } else { statusText = "離線"; } break; case "1": statusText = "在線"; break; case "2": statusText = "忙碌"; break; case "3": statusText = "離開"; break; case "4": statusText = "打盹"; break; case "5": statusText = "想交易"; break; case "6": statusText = "想游戲"; break; default: break; } status.Text = statusText; status.FontSize = (this.Height - 80) / 3; //狀態輔助賦值 if (!userdata["personastate"].ToString().Equals("0")) { try { extraText = userdata["gameextrainfo"].ToString() + " 游戲中"; username.Foreground = new SolidColorBrush(Colors.Green); status.Foreground = new SolidColorBrush(Colors.Green); extra.Foreground = new SolidColorBrush(Colors.Green); } catch { username.Foreground = new SolidColorBrush(Colors.Blue); status.Foreground = new SolidColorBrush(Colors.Blue); extra.Foreground = new SolidColorBrush(Colors.Blue); } } else { extraText = "上次在線時間:" + Static.UtoD(userdata["lastlogoff"].ToString()); username.Foreground = new SolidColorBrush(Colors.Gray); status.Foreground = new SolidColorBrush(Colors.Gray); extra.Foreground = new SolidColorBrush(Colors.Gray); } extra.Text = extraText; //頭像賦值 BitmapImage bitImg = new BitmapImage(new Uri(userdata["avatarfull"].ToString())); head.Source = bitImg; }
說明:
JSON格式的優勢在于,通過JObject["Name"] JArray[Index]就能獲得所需的數據,所占的體積小。

浙公網安備 33010602011771號