My Code goes like this:
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; }
}
IF JSON DATA EXISTS
{"SearchResponse":{"Version":"2.0","Query":{"SearchTerms":"mispell"},"Spell":{"Total":1,"Results":[{"Value":"misspell"}]}}}
IF JSON DATA DOES NOT EXIST
{"SearchResponse":{"Version":"2.0","Query":{"SearchTerms":"mispel"}}}
The thing is, if Bing doesn’t detect a wrong word, it crashes and gives me an error like NullReferenceException. I have tried to do an IF statement looking at the stream for if it’s value is blank but doesn’t seem to work.
Any ideas?
If you receive a JSON answer without the Spell part, the
Spellproperty inSearchResponsewill be null. If it’s null, you may not dereference it like this:(This hasn’t anything to do with JSON. It’s how C# works.)
So instead of:
you probably want to write:
For your next question: It would be very helpful if your questions would show the exact error message including the stack trace (or at least the exact line where it occurred).