0

I'm trying to return json data from a list within a list. The data is being pulled using a webclient and deserialized using JSON.NET. I'd like to return a name and image from the "featuredCharts" list which is within the "Results" list. Here is part of the json data I'm referring to.

"results":{
  "featuredCharts":[
     {
        "id":46082,
        "type":"chart",
        "name":"Exclusives On Beatport - Week 5",
        "slug":"exclusives-on-beatport-week-5",
        "description":"",
        "publishDate":"2012-01-30",
        "price":{
           "code":"usd",
           "symbol":"$",
           "value":2390
        },
        "audioFormatFee":{
           "wav":{
              "code":"usd",
              "symbol":"$",
              "value":1000
           },
           "aiff":{
              "code":"usd",
              "symbol":"$",
              "value":1000
           }
        },
        "genres":[
           {
              "id":11,
              "name":"Tech House",
              "slug":"tech-house",
              "type":"genre"
           },
           {
              "id":5,
              "name":"House",
              "slug":"house",
              "type":"genre"
           },
           {
              "id":17,
              "name":"Electro House",
              "slug":"electro-house",
              "type":"genre"
           },
           {
              "id":15,
              "name":"Progressive House",
              "slug":"progressive-house",
              "type":"genre"
           }
        ],
        "images":{
           "small":{
              "width":30,
              "height":30,
              "url":"http:\/\/geo-media.beatport.com\/items\/imageCatalog\/4000000\/900000\/50000\/1000\/200\/40\/4951247.jpg",
              "secureUrl":"https:\/\/media.beatport.com\/items\/imageCatalog\/4000000\/900000\/50000\/1000\/200\/40\/4951247.jpg"
           },
           "medium":{
              "width":60,
              "height":60,
              "url":"http:\/\/geo-media.beatport.com\/items\/imageCatalog\/4000000\/900000\/50000\/1000\/200\/40\/4951248.jpg",
              "secureUrl":"https:\/\/media.beatport.com\/items\/imageCatalog\/4000000\/900000\/50000\/1000\/200\/40\/4951248.jpg"
           },
           "large":{
              "width":130,
              "height":130,
              "url":"http:\/\/geo-media.beatport.com\/items\/imageCatalog\/4000000\/900000\/50000\/1000\/200\/40\/4951249.jpg",
              "secureUrl":"https:\/\/media.beatport.com\/items\/imageCatalog\/4000000\/900000\/50000\/1000\/200\/40\/4951249.jpg"
           },
           "xlarge":{
              "width":500,
              "height":500,
              "url":"http:\/\/geo-media.beatport.com\/items\/imageCatalog\/4000000\/900000\/50000\/1000\/200\/50\/4951250.jpg",
              "secureUrl":"https:\/\/media.beatport.com\/items\/imageCatalog\/4000000\/900000\/50000\/1000\/200\/50\/4951250.jpg"
           }
        },
        "chartOwner":null
     },

My classes are currently setup like this.

public class NewReleasesCharts //Root Object
{
    public Metadata metadata { get; set; }
    public List<ResultHome> results = new List<ResultHome>();

    public IEnumerator<ResultHome> GetEnumerator()
    {
        return this.results.GetEnumerator();
    }
}

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

public class FeaturedCharts
{
    public int id { get; set; }
    public string type { get; set; }
    public string name { get; set; }
    public string slug { get; set; }
    public ChartImages chartImages { get; set; }
}

public class ChartImages
{
    public ChartSmall chartSmall { get; set; }
    public ChartMedium chartMedium { get; set; }
    public ChartLarge chartLarge { get; set; }
}

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

This is the part I'm stuck on. After deserializing the data I'm using nested foreach loops, but i currently get an NullReferenceException error on rc.featuredCharts in the inner foreach loop. Here is the code.

    // Deserialize home page data
    void jsonHome_GetDataCompleted(object snder, DownloadStringCompletedEventArgs e)
    {
        NewReleasesCharts homeData = JsonConvert.DeserializeObject<NewReleasesCharts>(e.Result);
        try
        {
            // Nested foreach loops to dispaly data
            foreach (ResultHome rc in homeData)
            {
                foreach (FeaturedCharts fc in rc.featuredCharts)
                {
                    // TODO: return name and image of chart
                    string name = fc.name;
                    listGenres.Items.Add(name);
                }
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.ToString());
        }
    }

I'm still a beginner when it comes to c# so i'm not sure what I'm doing wrong. An example of how to do this properly would give me something to build off of, as i'll need to do this in other parts of my app.

Thanks.

UPDATE Here is the full exception:

System.NullReferenceException was unhandled

Message=NullReferenceException StackTrace: at Beatport.MainPage.jsonHome_GetDataCompleted(Object snder, DownloadStringCompletedEventArgs e) at System.Net.WebClient.OnDownloadStringCompleted(DownloadStringCompletedEventArgs e) at System.Net.WebClient.DownloadStringOperationCompleted(Object arg) at System.Reflection.RuntimeMethodInfo.InternalInvoke(RuntimeMethodInfo rtmi, Object obj, BindingFlags invokeAttr, Binder binder, Object parameters, CultureInfo culture, Boolean isBinderDefault, Assembly caller, Boolean verifyAccess, StackCrawlMark& stackMark) at System.Reflection.RuntimeMethodInfo.InternalInvoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, StackCrawlMark& stackMark) at System.Reflection.MethodBase.Invoke(Object obj, Object[] parameters) at System.Delegate.DynamicInvokeOne(Object[] args) at System.MulticastDelegate.DynamicInvokeImpl(Object[] args) at System.Delegate.DynamicInvoke(Object[] args) at System.Windows.Threading.DispatcherOperation.Invoke() at System.Windows.Threading.Dispatcher.Dispatch(DispatcherPriority priority) at System.Windows.Threading.Dispatcher.OnInvoke(Object context) at System.Windows.Hosting.CallbackCookie.Invoke(Object[] args) at System.Windows.Hosting.DelegateWrapper.InternalInvoke(Object[] args) at System.Windows.RuntimeHost.ManagedHost.InvokeDelegate(IntPtr pHandle, Int32 nParamCount, ScriptParam[] pParams, ScriptParam& pResult)

nos9
  • 381
  • 2
  • 3
  • 15
  • possible duplicate of [What is a NullReferenceException in .NET?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-in-net) – John Saunders Feb 16 '12 at 02:55
  • Also, I suggest you get out of the habit of using try/catch blocks everywhere. It's generally best to allow the exception to propagate as high in the stack as practical. So _maybe_ your code should have one, outer `try/catch/MessageBox.Show(ex.ToString());` Note that ex.Message only outputs the message text, and you'll want to display the full exception. – John Saunders Feb 16 '12 at 02:57
  • Hard to say just looking at the code, but if you set a breakpoint on `foreach (FeaturedCharts fc in rc.featuredCharts)` what is the contents of `rc.featuredCharts` ? – Alan Feb 16 '12 at 02:59
  • Is your variable "listCharts" initialized? – David Spence Feb 16 '12 at 03:00
  • @JohnSaunders Thanks for the tip. I tried a try/catch right before the outer loop, but the full exception is to convoluted for me to understand what is going wrong. – nos9 Feb 16 '12 at 03:44

2 Answers2

0

It's hard to say because the json object you posted looks good, but it's incomplete.

Start here: http://json2csharp.com/

compare the classes that that generates to your own.

NotMe
  • 84,830
  • 27
  • 167
  • 241
  • I tried that already, but for some reason it doesn't work for this particular json string. I had build the class on my own – nos9 Feb 16 '12 at 03:33
0

If the exception occurs on the line string name = fc.name;, then fc must be null, as unlikely as that seems.

John Saunders
  • 157,405
  • 24
  • 229
  • 388