I'm currently using an API to grab some player information, which looks like this in raw data form:
{
"response": {
"players": [
{
"steamid": "76561198166559342",
"communityvisibilitystate": 1,
"profilestate": 1,
"personaname": "Stack Overflow",
"commentpermission": 2,
"profileurl": "https://steamcommunity.com/id/stackoverflow/",
"avatar": "https://avatars.akamai.steamstatic.com/8a2e52a3eaefed0296459fa811aasdasd1ce29374.jpg",
"avatarmedium": "https://avatars.akamai.steamstatic.com/8a2e52a3eaefed0296459fa81asdas1ce29374_medium.jpg",
"avatarfull": "https://avatars.akamai.steamstatic.com/8a2e52a3eaefed0296459fa811a61212312e29374_full.jpg",
"avatarhash": "8a2e52a3eaefed02asdasd",
"personastate": 0
}
]
}
}
I am trying to just grab the "personaname" and "avatar" values from my data, which have been quite unsuccessful, so I've tried to objectify the JSON before getting it, which still isn't working:
Models.SteamUser persona;
String httpres;
using (var client = new HttpClient())
{
string steamurl = "MY HIDDEN URL HERE" + s64;
var steamapi = new Uri(steamurl);
var result = client.GetAsync(steamapi).Result.Content.ReadAsStringAsync().Result;
var json = result.ToString();
httpres = json;
var jUser = JObject.Parse(json);
var userData = JsonConvert.DeserializeObject<Models.SteamUser>(jUser["players"]).ToString(); ;
persona = userData;
}
Is there something I'm missing?
To get players
from the JSON response, you need jObj["response"]["players"]
instead of jObj["players"]
.
You have to deserialize as List<Models.SteamUser>
but not Models.SteamUser
as it is an array. Then with IEnumerable.FirstOrDefault()
to get the first item of the array.
From the existing code, the userData
is string
type while persona
is List<Models.SteamUser>
type. You can't assign userData
to persona
.
Not suggested using Task.Result
as it performs the operation synchronously and waits for the operation to be completed. Hence, it may lead to a deadlock. Instead, works with async
/ await
. Source: What happens while waiting on a Task's Result?
Your code should be looked as below:
Models.SteamUser persona = null;
using (var client = new HttpClient())
{
string steamurl = "MY HIDDEN URL HERE" + s64;
var steamapi = new Uri(steamurl);
var response = await client.GetAsync(steamapi);
var jsonResult = await response.Content.ReadAsStringAsync();
var jObj = JObject.Parse(jsonResult);
var players = JsonConvert.DeserializeObject<List<Models.SteamUser>>(jObj["response"]["players"].ToString());
// Or
// var players = (jObj["response"]["players"] as JArray).ToObject<List<Models.SteamUser>>();
persona = players.FirstOrDefault();
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.