1

I created a HTTPWebRequest to check if the username and password of the user is correct. If the username and password of the user is correct it will return a JSON Array with the ContactID of the user. I tried to deserialize the JSON but I failed to get the actual data. I want to get the Contact id and send the data to a variable of the next page.

The output of the JSON when the username and password is correct:

[{"ContactID":"1"}]

My code:

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Net;
using System.Text;
using System.Windows.Input;
using TBSMobileApplication.Data;
using TBSMobileApplication.View;
using Xamarin.Essentials;
using Xamarin.Forms;

namespace TBSMobileApplication.ViewModel
{
    public class LoginPageViewModel : INotifyPropertyChanged
    {
        void OnProperyChanged(string PropertyName)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(PropertyName));
        }

        public string username;
        public string password;

        public string Username
        {
            get { return username; }
            set
            {
                username = value;
                OnProperyChanged(nameof(Username));
            }
        }

        public string Password
        {
            get { return password; }
            set
            {
                password = value;
                OnProperyChanged(nameof(Password));
            }
        }

        public ICommand LoginCommand { get; set; }

        public LoginPageViewModel()
        {
            LoginCommand = new Command(OnLogin);
        }

        public void OnLogin()
        {
            if (string.IsNullOrEmpty(Username) || string.IsNullOrEmpty(Password))
            {
                MessagingCenter.Send(this, "Login Alert", Username);
            }
            else
            {
                var current = Connectivity.NetworkAccess;

                if (current == NetworkAccess.Internet)
                {
                    var link = "http://192.168.1.25:7777/TBS/test.php?User=" + Username + "&Password=" + Password;
                    var request = HttpWebRequest.Create(string.Format(@link));
                    request.ContentType = "application/json";
                    request.Method = "GET";

                    using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
                    {
                        if (response.StatusCode != HttpStatusCode.OK)
                        {
                            Console.Out.WriteLine("Error fetching data. Server returned status code: {0}", response.StatusCode);
                        }
                        else
                        {
                            using (StreamReader reader = new StreamReader(response.GetResponseStream()))
                            {
                                var content = reader.ReadToEnd();

                                if (content.Equals("[]") || string.IsNullOrWhiteSpace(content) || string.IsNullOrEmpty(content))
                                {
                                    MessagingCenter.Send(this, "Http", Username);
                                }
                                else
                                {
                                    var usr = JsonConvert.DeserializeObject(content);
                                    App.Current.MainPage.Navigation.PushAsync(new DatabaseSyncPage(), true);
                                }
                            }
                        }
                    }
                }
                else
                {
                    MessagingCenter.Send(this, "Not Connected", Username);
                }
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;
    }
}

2 Answers2

1

Modify your code else block like below

if (content.Equals("[]") || string.IsNullOrWhiteSpace(content) || string.IsNullOrEmpty(content))
{
    MessagingCenter.Send(this, "Http", Username);
}
else
{
    var response = JsonConvert.DeserializeObject<List<LoggedInUser>>(content);   
    var contactId=response[0].ContactID;
    //response have your ContactID value. Try to debug & see.
    App.Current.MainPage.Navigation.PushAsync(new DatabaseSyncPage(), true);
}

Create one another public class to deserialize your response

public class LoggedInUser
{
    public string ContactID { get; set; }
}

If you have more than 1 record in result(as you asked this in comment below) you can get them using loops

for (int i = 0; i < response.Count; i++)
{
   var item = response[i];
   var contactId = item.ContactId;
}

Hope it help you.

R15
  • 13,982
  • 14
  • 97
  • 173
  • How can I pass the value to a variable to the next page? –  Jul 26 '18 at 05:39
  • 1
    `response` have ContactID value in your else block. Try to debug & see what coming in response. – R15 Jul 26 '18 at 05:40
  • Do the Json Array Name be the same with the public string ContactID { get; set; } or not necessarily? –  Jul 26 '18 at 05:44
  • there is an error "Newtonsoft.Json.JsonSerializationException: Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'TBSMobileApplication.ViewModel.LoginPageViewModel+LoggedInUser' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly." –  Jul 26 '18 at 05:47
  • But I didn't get the ContactID because there is an error –  Jul 26 '18 at 05:52
  • 1
    Yes, This is correct exception because there is no Json properties in class to deserialize this object{"name":"value"} . And According to Exception Json is coming in Array format. So you should use like this - var response = JsonConvert.DeserializeObject>(content); – Pratius Dubey Jul 26 '18 at 05:52
  • @Arvindraja when I see the response value it's value is "Count=1" not the actual value –  Jul 26 '18 at 06:22
  • @Arvindraja last questions how about there are more that 5 count how can I get all the data? –  Jul 26 '18 at 07:01
  • Thank you so much you really help a lot sorry for many question I am new to Xamarin –  Jul 26 '18 at 07:08
  • Done sir, now I just neet to pass the data to my datasync page any recommendations? –  Jul 26 '18 at 07:11
  • Make another question for that. Instead of dragging this thread. We will discus there. – R15 Jul 26 '18 at 07:13
  • @Arvindraja please see https://stackoverflow.com/questions/51533628/xamarin-mvvm-passing-data-to-other-view –  Jul 26 '18 at 07:50
0

JSON Response object is not looking standard format for output result. Whatever for JSON deserialization you should create separate class as per below code.

       public class RootObject
    {
        public string ContactID { get; set; }
    }

    Public Void ServiceRequest()
    {
      var content = reader.ReadToEnd();
     if(!String.IsNullOrEmpty(content)
    {
      var response = JsonConvert.DeserializeObject<RootObject>(content);
    }
}

I hope it will be useful.

Pratius Dubey
  • 673
  • 6
  • 19