2017-09-23 52 views
0

对C#来说相当新颖,希望有任何帮助。json的反序列化在正确格式化的json中返回null

获取以下错误: “未将对象引用设置为对象的实例”。当我尝试访问recipeinforeturned.resultslist [0] .title或列表中的任何其他元素。

但是,我能够成功返回recipereturned.title。

下面是使用JSON格式的API网址:

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

} 任何帮助将不胜感激。

+0

1.使用http://jsonutils.com从JSON(-Url)构建您的类 - 2.使用JSON.Net对于JSON序列化 –

回答

0

您需要重命名:

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

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

否则解串器正在寻找在你的JSON对象resultslist但无法找到它,因此返回null

0

您可以尝试将“版本”字符串的字段类型更改为双倍。

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

其实你解决了我的问题。我以错误的名字在班上打了电话。我只是看着你的回应。非常感谢!! – JBiz