我的代码是这样的:
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语句查看流,如果它的值是空白但似乎不起作用。
有什么想法吗?
答案 0 :(得分:0)
使用[DataMember(IsRequired = false)],MSDN:http://msdn.microsoft.com/en-us/library/system.runtime.serialization.datamemberattribute.isrequired.aspx
答案 1 :(得分:0)
如果您收到没有拼写部分的JSON答案,Spell
中的SearchResponse
属性将 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>();
对于您的下一个问题:如果您的问题会显示包含堆栈跟踪的确切错误消息(或至少是它出现的确切行),那将非常有用。