使用无效的变量名称反序列化嵌套的json

时间:2017-08-30 15:42:24

标签: c# json httpwebrequest json-deserialization

我正在使用C#中的Last.FM API。我之前没有使用过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变量为null。

我编写的代码将导航到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; }
    }

1 个答案:

答案 0 :(得分:1)

使用this site,您的模型应该是这样的

public class Artist
{
    public string name { get; set; }
    public string mbid { get; set; }
    public string url { get; set; }
}

public class Image
{
    [JsonProperty("#text")]
    public string text { get; set; }
    public string size { get; set; }
}

public class Attr
{
    public string rank { get; set; }
}

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> image { get; set; }
    [JsonProperty("@attr")]
    public Attr attr { get; set; }
}

public class Attr2
{
    public string user { get; set; }
    public string page { get; set; }
    public string perPage { get; set; }
    public string totalPages { get; set; }
    public string total { get; set; }
}

public class Topalbums
{
    public List<Album> album { get; set; }
    [JsonProperty("@attr")]
    public Attr2 attr { get; set; }
}

public class RootObject
{
    public Topalbums topalbums { get; set; }
}

您现在可以反序列化为

var result = JsonConvert.DeserializeObject<RootObject>(json);