缺少JSON字段会导致崩溃

本文关键字:崩溃 JSON 字段 缺少 | 更新日期: 2023-09-27 18:26:16

我的代码如下:

    using (StreamReader streamReader1 = new StreamReader(response.GetResponseStream()))
    {
        string resultString = streamReader1.ReadToEnd();
        var ser = new DataContractJsonSerializer(typeof(RootObject));
        var stream = new MemoryStream(Encoding.Unicode.GetBytes(resultString));
        DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof(RootObject));
        RootObject myBook = (RootObject)jsonSerializer.ReadObject(stream);
        Deployment.Current.Dispatcher.BeginInvoke(() => Shops.ItemsSource = myBook.SearchResponse.Spell.Results); }
  public class Query
    {
        public string SearchTerms { get; set; }
    }

    public class Result
    {   [DataMember(IsRequired=false)]
        public string Value { get; set; }
    }
    public class Spell
    {
        [DataMember(IsRequired = false)]
        public int Total { get; set; }
        [DataMember(IsRequired = false)]
        public List<Result> Results { get; set; }
    }
    public class SearchResponse
    {
        public bool IsRequired { get; set; }
        public string Version { get; set; }
        public Query Query { get; set; }
        public Spell Spell { get; set; }
    }
    public class RootObject
    {
        public SearchResponse SearchResponse { get; set; }
    }

如果JSON数据存在

  {"SearchResponse":{"Version":"2.0","Query":{"SearchTerms":"mispell"},"Spell":{"Total":1,"Results":[{"Value":"misspell"}]}}}

如果JSON数据不存在

  {"SearchResponse":{"Version":"2.0","Query":{"SearchTerms":"mispel"}}}

问题是,如果Bing没有检测到错误的单词,它就会崩溃,并给我一个错误,比如NullReferenceException。我试着做一个IF语句,查看流的值是否为空,但似乎不起作用。

有什么想法吗?

缺少JSON字段会导致崩溃

如果您收到一个没有拼写部分的JSON应答,则SearchResponse中的Spell属性将为null。如果null,您可能不会像这样取消引用它:

myBook.SearchResponse.Spell.Results

(这与JSON无关。这是C#的工作方式。)

所以不是:

Shops.ItemsSource = myBook.SearchResponse.Spell.Results

你可能想写:

if (myBook.SearchResponse.Spell = null)
    Shops.ItemsSource = myBook.SearchResponse.Spell.Results;
else
    Shops.ItemsSource = new List<Result>();

对于您的下一个问题:如果您的问题能够显示确切的错误消息,包括堆栈跟踪(或者至少显示发生错误的确切行),这将非常有帮助。

使用[DataMember(IsRequired=false)],MSDN:http://msdn.microsoft.com/en-us/library/system.runtime.serialization.datamemberattribute.isrequired.aspx