WP7 NullReferenceException反序列化JSON数组

时间:2012-04-03 02:42:52

标签: c# json windows-phone-7 json.net

我一直无法将JSON数据从网络上移到我的应用中。我正在尝试从“featuredReleases”数组中提取名称和图像。这是JSON的一部分:

      "featuredReleases":[
     {
        "id":860118,
        "type":"release",
        "name":"Back In Time",
        "slug":"back-in-time",
        "releaseDate":"2012-01-30",
        "publishDate":"2012-01-30",
        "exclusive":true,
        "category":"Release",
        "description":"Toolroom Records breaks new ground once again courtesy of the legendary drum and bass double act Liquid Kaos who have teamed up with vocalist Kirsty Hawkshaw for Back In Time, a drum and bass master class that will be taking over the airwaves and the clubs. Liquid Kaos need little introduction as owners of the legendary Breakbeat Kaos imprint and an impressive list of accolades between them that includes multiple UK Top 10 singles, a Mobo award and the support of the scenes most influential players Zane Lowe, Fabio & Grooverider, Mistajam and more. The most distinctive voice in dance music and a number 1 selling artist in her own right, Kirsty Hawkshaw completes this dream collaboration. Back In Time hooks you in with the haunting vocals of Kirsty Hawkshaw swirling above searing synths and atmospheric strings before dropping into organic grooves and a delectably warm bass. On the remix tip, Swedish star John Dahlb\u00e4ck provides a four to the floor electro workout, dubsteps rising star Cookie Monsta throws in a big, bass heavy re-rub whilst Toolrooms new wonder kid CaPa and Germanys deep house duo Kruse & N\u00fcrnberg complete a versatile package.",
        "currentStatus":"New Release",
        "catalogNumber":"TOOL12902Z",
        "purchasable":true,
        "images":{
           "small":{
              "width":30,
              "height":30,
              "url":"http:\/\/geo-media.beatport.com\/items\/imageCatalog\/4000000\/900000\/0\/9000\/500\/70\/4909578.jpg",
              "secureUrl":"https:\/\/media.beatport.com\/items\/imageCatalog\/4000000\/900000\/0\/9000\/500\/70\/4909578.jpg"
           },
           "medium":{
              "width":60,
              "height":60,
              "url":"http:\/\/geo-media.beatport.com\/items\/imageCatalog\/4000000\/900000\/0\/9000\/500\/70\/4909579.jpg",
              "secureUrl":"https:\/\/media.beatport.com\/items\/imageCatalog\/4000000\/900000\/0\/9000\/500\/70\/4909579.jpg"
           },
           "large":{
              "width":500,
              "height":500,
              "url":"http:\/\/geo-media.beatport.com\/items\/imageCatalog\/4000000\/900000\/0\/9000\/500\/80\/4909580.jpg",
              "secureUrl":"https:\/\/media.beatport.com\/items\/imageCatalog\/4000000\/900000\/0\/9000\/500\/80\/4909580.jpg"
           }
        }
     },

如果你需要查看完整的JSON(它真的很长),这里是插入JSON Formatter的api。 http://api.beatport.com/catalog/3/beatport/home

这是我的课程。

namespace Beatport.Classes
{
    public class NewReleasesCharts //Root Object
    {
        public Metadata metadata { get; set; }
        public ResultHome results = new ResultHome();
    public IEnumerator<ResultHome> GetEnumerator()
    {
        return this.results.GetEnumerator();
    }
}

public class ResultHome
{
    public List<FeaturedReleases> featuredReleases { get; set; }

    //public List<FeaturedCharts> featuredCharts { get; set; }
    //public List<TopDownloads> topdownloads { get; set; }
    //public List<MostPopularReleases> mostPopularReleases { get; set; }
    //public List<Components> components { get; set; }

    internal IEnumerator<ResultHome> GetEnumerator()
    {
        throw new NotImplementedException();
    }
}

public class FeaturedReleases
{
    public int id { get; set; }
    public string type { get; set; }
    public string name { get; set; }
    public string slug { get; set; }
    public ReleaseImage releaseImage { get; set; } 
}

public class ReleaseImage
{
    public ReleaseSmall releaseSmall { get; set; }
    public ReleaseMedium releaseMedium { get; set; }
    public ReleaseLarge releaseLarge { get; set; }
}

public class ReleaseMedium
{
    public int width { get; set; }
    public int height { get; set; }
    public string url { get; set; }
    public string secureUrl { get; set; }
}  

最后,这是我的反序列化JSON(使用json.net)并提取数据的处理程序。

已更新

    // Deserialize home page data
    void jsonHome_GetDataCompleted(object snder, DownloadStringCompletedEventArgs e)
    {
        try
        {
            NewReleasesCharts homeData = JsonConvert.DeserializeObject<NewReleasesCharts>(e.Result);

            foreach (FeaturedReleases release in homeData.results.featuredReleases)
            {
                string releaseName = release.name;
                string img = release.releaseImage.releaseMedium.url;
                listGenres.Items.Add(releaseName);
                listGenres.Items.Add(img);
            }

        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }

    }

我在尝试反序列化NewReleasesCharts时遇到了json.net异常。

Cannot deserialize JSON array (i.e. [1,2,3]) into type 'Beatport.Classes.ResultHome'. The deserialized type must be an array or implement a collection interface like IEnumerable, ICollection or IList. To force JSON arrays to deserialize add the JsonArrayAttribute to the type. Line 1, position 58.

1 个答案:

答案 0 :(得分:1)

你非常接近解决方案。

首先,反序列化为

NewReleasesCharts homeData = JsonConvert.DeserializeObject<NewReleasesCharts>(e.Result)

然后将您的班级定义更改为

public class FeaturedReleases
{
    public int id { get; set; }
    public string type { get; set; }
    public string name { get; set; }
    public string slug { get; set; }
    public ReleaseImage images { get; set; }
}

public class ReleaseImage
{
    public ReleaseSmall small { get; set; }
    public ReleaseMedium medium { get; set; }
    public ReleaseLarge large { get; set; }
}

最后,你的循环应该是这样的

foreach (FeaturedReleases release in homeData.results.featuredReleases)
{
    string releaseName = release.name;
    string img = release.images.medium.url;
    listGenres.Items.Add(releaseName);
    listGenres.Items.Add(img);
}