0
我正在玩C#中的Last.FM API。我之前没有用过Json,所以这对我来说有点新鲜。反序列化具有无效变量名称的嵌套json
的JSON我试图解析像
"{
\"topalbums\": {
\"album\": [
{
\"name\": \"California (Deluxe Edition)\",
\"playcount\": \"89\",
\"mbid\": \"\",
\"url\": \"https: \/\/www.last.fm\/music\/blink-182\/California+(Deluxe+Edition)\",
\"artist\": {
\"name\": \"blink-182\",
\"mbid\": \"0743b15a-3c32-48c8-ad58-cb325350befa\",
\"url\": \"https: \/\/www.last.fm\/music\/blink-182\"
},
\"image\": [
{
\"#text\": \"https: \/\/lastfm-img2.akamaized.net\/i\/u\/34s\/ccd85fcfa4370e1df83a67c7fa79096c.png\",
\"size\": \"small\"
},
{
\"#text\": \"https: \/\/lastfm-img2.akamaized.net\/i\/u\/64s\/ccd85fcfa4370e1df83a67c7fa79096c.png\",
\"size\": \"medium\"
},
{
\"#text\": \"https: \/\/lastfm-img2.akamaized.net\/i\/u\/174s\/ccd85fcfa4370e1df83a67c7fa79096c.png\",
\"size\": \"large\"
},
{
\"#text\": \"https: \/\/lastfm-img2.akamaized.net\/i\/u\/300x300\/ccd85fcfa4370e1df83a67c7fa79096c.png\",
\"size\": \"extralarge\"
}
],
\"@attr\": {
\"rank\": \"1\"
}
},
我的代码看起来反序列化JSON的样子
public List<TopAlbum> GetTopAlbumsDeserialized(int limit)
{
List<TopAlbum> topAlbumList = new List<TopAlbum>();
var request = (HttpWebRequest)WebRequest.Create(
webServiceURL + "/2.0/?method=user.gettopalbums&user=" + user + "&api_key=" + key + "&format=json");
if (limit > 0)
{
request = (HttpWebRequest)WebRequest.Create(
webServiceURL + "/2.0/?method=user.gettopalbums&user=" + user + "&limit=" + limit
+ "&api_key=" + key + "&format=json");
}
request.ContentType = "application/json; charset=utf-8";
request.Method = WebRequestMethods.Http.Get;
request.Accept = "application/json";
var response = (HttpWebResponse)request.GetResponse();
using (var sr = new StreamReader(response.GetResponseStream()))
{
string responseString = sr.ReadToEnd();
sr.Close();
JContainer jContainer = JObject.Parse(responseString);
JArray topAlbumsArray = JArray.FromObject(jContainer.First().First().First().First());
JObject.FromObject(jContainer.First().First().First().First()["image"]);
topAlbumList = JsonConvert.DeserializeObject<List<TopAlbum>>(topAlbumsArray.ToString());
}
return topAlbumList;
}
我的代码反序列化的专辑一开始就有些工作大多正常。但是,当我查看返回的List时,对于每个Album对象,我的图像列表是空的,并且rank变量为空。
我编写的代码将导航到json中的专辑数组,只是解析每个专辑,但它看起来不太好。尽管如此,我认为我没有为Image和TopAlbum类正确编写JsonPropertys。
这里是我的对象供参考。
public class Album
{
public string name { get; set; }
public string playcount { get; set; }
public string mbid { get; set; }
public string url { get; set; }
public Artist artist { get; set; }
public List<Image> images { get; set; }
}
public class TopAlbum : Album
{
public string rank { get; set; }
}
public class Image
{
[JsonProperty("#text")]
public string text {get; set;}
public string size { get; set; }
}
public class Artist
{
public string name { get; set; }
public string mbid { get; set; }
public string url { get; set; }
}
谢谢! 绝对要将该网站加入书签。 –