Search code examples
c#asp.netjsonclassjson-deserialization

deserialization of json return null in properly formatted json


Fairly new to C# and would appreciate any help.

Getting the following error: "Object reference not set to an instance of an object." when I attempt access a recipeinforeturned.resultslist[0].title or any other elements in the list.

I am able to return recipereturned.title successfully, however.

Here's the api URL with json format:

http://www.recipepuppy.com/api/?i=onions,garlic&q=omelet&p=3

    protected void getButton_Click(object sender, EventArgs e)
    {
        string url = string.Format("http://www.recipepuppy.com/api/?i={0}&q={1}", ingredientsTextBox.Text, recipetypeTextBox.Text);

        using (WebClient client = new WebClient())
        {
            string json = client.DownloadString(url);
            RecipeInfo recipeinforeturned = new RecipeInfo();
            recipeinforeturned = (new JavaScriptSerializer()).Deserialize <RecipeInfo>(json);
            //next need a loop to go through each list item and add to ResultsListBox to end of recipies
            Label1.Text = recipeinforeturned.title;
            for (int i = 0; i < recipeinforeturned.resultslist.Count; i++)

            {
               resultsListBox.Items.Add(recipeinforeturned.resultslist[i].title);
                resultsListBox.Items.Add(recipeinforeturned.resultslist[i].ingredients);
                resultsListBox.Items.Add(Environment.NewLine);
            }
        }


    }

    public class RecipeInfo
    {      
        public string title { get; set; }
        public string version { get; set; }
        public string href { get; set; }
        public List<Results> resultslist { get; set; }
    }

    public class Results

    {
        public string title { get; set; }
        public string href { get; set; }
        public string ingredients { get; set; }
        public string thumbnail { get; set; }
    }
}

} Any help would be greatly appreciated.


Solution

  • You need to rename:

    public List<Results> resultslist { get; set; }
    

    to

    public List<Results> results { get; set; }
    

    Otherwise deserialiser is looking for resultslist object in your JSON but can't find it, therefore returns null