Suraj
Suraj

Reputation: 433

system.runtime.serialization.serializationException was thrown

I want to run following delegate in my xamarin android project.

But after running this ,an object S of State class contains null. And this error points to the following line in code.

tv.Text = s.name+""+s.population;

tv is a textview in my code.

button.Click += async delegate {

    state s = new state();
    HttpClient _client = new HttpClient();
    string url = "http://iforindia.azurewebsites.net/api/state/uid/33F8A8D5-0DF2-47A0-9C79-002351A95F88";
    HttpResponseMessage response = await _client.GetAsync(url);
    if (response.ReasonPhrase.Contains("OK"))
    {
        if (response != null)
        {
            var jsonSerializer = new DataContractJsonSerializer(typeof(state));
            var stream = await response.Content.ReadAsStreamAsync();
            s= (state)jsonSerializer.ReadObject(stream);
        }
    }
    else if (response.ReasonPhrase.Contains("Bad Request"))
    {
        s= null;
    }
    else
    {
        s= null;
    }
    tv.Text = s.name+""+s.population;
};

Upvotes: 0

Views: 444

Answers (1)

SKall
SKall

Reputation: 5234

This is redundant (response.ReasonPhase would have already raised a null exception):

if (response != null)

Try this:

 button.Click += async delegate {

    var client = new HttpClient();
    var url = "http://iforindia.azurewebsites.net/api/state/uid/33F8A8D5-0DF2-47A0-9C79-002351A95F88";
    var response = await _client.GetAsync(url);
    if (response != null && response.ReasonPhrase.Contains("OK"))
    {
            var jsonSerializer = new DataContractJsonSerializer(typeof(state));
            var stream = await response.Content.ReadAsStreamAsync();
            var s = jsonSerializer.ReadObject(stream) as state;

            if (s != null)
            {
                 tv.Text = s.name+""+s.population;
            }   
        }
   };

Upvotes: 2

Related Questions