无法反序列化JSON数据



我目前正在使用API来获取一些玩家信息,这看起来像这样的原始数据形式:

{
"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
}
]
}
}

我只是想抓住" personname "one_answers";avatar"值从我的数据,这已经相当不成功,所以我已经试图客观化JSON之前得到它,这仍然不工作:

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;
}

我错过了什么吗?

  1. 要从JSON响应中获得players,您需要jObj["response"]["players"]而不是jObj["players"]

  2. 您必须反序列化为List<Models.SteamUser>而不是Models.SteamUser,因为它是一个数组。然后使用IEnumerable.FirstOrDefault()获取数组的第一项。

  3. 从现有代码来看,userDatastring型,personaList<Models.SteamUser>型。不能将userData分配给persona

  4. 不建议使用Task.Result,因为它同步执行操作并等待操作完成。因此,它可能导致死锁。相反,使用async/await。来源:等待任务结果时会发生什么?

你的代码应该看起来如下:

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();
}

相关内容

  • 没有找到相关文章

最新更新