簡體   English   中英

json的反序列化在格式正確的json中返回null

[英]deserialization of json return null in properly formatted json

對C#來說還很新,不勝感激。

得到以下錯誤:“對象引用未設置為對象的實例。” 當我嘗試訪問配方inforeturned.resultslist [0] .title或列表中的任何其他元素時。

但是,我能夠成功返回配方returned.title。

這是json格式的api URL:

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; }
    }
}

} 任何幫助將不勝感激。

您可以嘗試將“版本”字符串的字段類型更改為雙精度。

 public class RootObject
{
    public string title { get; set; }
    public double version { get; set; }
    public string href { get; set; }
    public List<Result> results { get; set; }
}

您需要重命名:

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

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

否則,反序列化程序會在JSON中尋找resultslist對象,但找不到它,因此返回null

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM