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"]))[];
//昵称赋值、溢出部分使用省略号代替
username.Text = userdata["personaname"].ToString();
username.TextTrimming = TextTrimming.WordEllipsis;
username.FontSize = (this.Height - ) / ;
//状态赋值
switch (userdata["personastate"].ToString())
{
case "":
if (userdata["communityvisibilitystate"].ToString().Equals(""))
{
statusText = "该用户资料未公开";
}
else
{
statusText = "离线";
}
break;
case "":
statusText = "在线";
break;
case "":
statusText = "忙碌";
break;
case "":
statusText = "离开";
break;
case "":
statusText = "打盹";
break;
case "":
statusText = "想交易";
break;
case "":
statusText = "想游戏";
break;
default: break;
}
status.Text = statusText;
status.FontSize = (this.Height - ) / ;
//状态辅助赋值
if (!userdata["personastate"].ToString().Equals(""))
{
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]就能获得所需的数据,所占的体积小。

上一篇:01_2Java开发环境的下载 安装 配置


下一篇:【windows7 + Appium】之Appium安装以及其他工具安装配置