How to receive response from server in Xamarin.Forms

Viewed 1041

I have created an HTTP Client that sends data to my server. This data will query my server that will return a JSON object. How can I receive the JSON Object response from my server and insert it into my database?

The code below will send a ContactID to my server and my server will return a JSON Object How can I get the JSON Object from my server? What will I add to my code? I have added

var data = await response.Content.ReadAsStringAsync();

but I don't know how to proceed.

try
        {
            var db = DependencyService.Get<ISQLiteDB>();
            var conn = db.GetConnection();

            var sql = "SELECT * FROM tblUser WHERE ContactID = '" + contact + "'";
            var getUser = conn.QueryAsync<UserTable>(sql);
            var resultCount = getUser.Result.Count;

            //Check if the user has been sync
            if (resultCount < 1)
            {
                try
                {
                    syncStatus.Text = "Syncing user to server...";

                    var link = Constants.requestUrl + "Host=" + host + "&Database=" + database + "&Contact=" + contact + "&Request=8qApc8";
                    string contentType = "application/json";
                    JObject json = new JObject
                    {
                        { "ContactID", contact }
                    };

                    HttpClient client = new HttpClient();
                    var response = await client.PostAsync(link, new StringContent(json.ToString(), Encoding.UTF8, contentType));
                    var data = await response.Content.ReadAsStringAsync();

                    if (response.IsSuccessStatusCode)
                    {
                        var content = await response.Content.ReadAsStringAsync();
                        var userresult = JsonConvert.DeserializeObject<IList<UserData>>(content);
                        var count = userresult.Count;

                        for (int i = 0; i < count; i++)
                        {
                            try
                            {
                                syncStatus.Text = "Syncing user to server...";

                                var item = userresult[i];
                                var contactID = item.ContactID;
                                var userID = item.UserID;
                                var userPassword = item.UserPassword;
                                var userType = item.UserType;
                                var userStatus = item.UserStatus;
                                var lastSync = item.LastSync;
                                var serverUpdate = item.ServerUpdate;
                                var mobileUpdate = item.MobileUpdate;

                                var user = new UserTable
                                {
                                    ContactID = Convert.ToInt32(contactID),
                                    UserID = userID,
                                    UserPassword = userPassword,
                                    UserType = userType,
                                    UserStatus = userStatus,
                                    LastSync = lastSync,
                                    ServerUpdate = serverUpdate,
                                    MobileUpdate = mobileUpdate
                                };

                                await conn.InsertAsync(user);
                            }
                            catch (Exception ex)
                            {
                                Console.Write("Syncing user error " + ex.Message);
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.Write("Syncing User Error " + ex.Message);
                }
            }

My PHP code will query my database with the ContactID received from Xamarin HTTP Client.

$json_str = file_get_contents('php://input');
    $json_obj = json_decode($json_str);

    $ContactID = $json_obj->ContactID;

    $sql = "SELECT * FROM tblUser WHERE ContactID = '$ContactID'";
    $result = mysqli_query($conn, $sql);
    $count = mysqli_num_rows($result);

    if($count > 0){
        while ($row = @mysqli_fetch_array($result)) {
            $decr = CryptRC4(FromHexDump($row['UserPassword']), $key);

            $ar[] = array(
                'ContactID' => $row['ContactID'],
                'UserID' => $row['UserID'],
                'UserPassword' => $decr,
                'UserType' => $row['UserType'],
                'UserStatus' => $row['UserStatus'],
                'LastSync' => $sync,
                'ServerUpdate' => $row['ServerUpdate'],
                'MobileUpdate' => $row['MobileUpdate']
            );

            print json_encode($ar);

            //Update LastSync DateTime
            $sql = "UPDATE tblUser SET LastSync = '$sync' WHERE ContactID = '$ContactID'";
            mysqli_query($conn, $sql);
        }
    }    
3 Answers

Last statement in your example above gives list of json objects in string format.

var data = await response.Content.ReadAsStringAsync();

You need to convert that back to list of objects. To let your project know about definition of the object, create a plain class with public properties (Something like below)

public class UserLog
{
    public int ContactId { get; set; }
    public string Log { get; set; }
    public DateTime LogDate { get; set; }
}

Add Newtonsoft.Json (by James Newton-King) Nuget package to your project so that you can work with json.

To convert content of the variable 'data' into list of UserLog objects, write code like

var list = NewtonsoftUtil<IList<UserLog>>.DeserializeObject(data);

(Add using Newtonsoft.Json; at top of the file)

Please let me know if this helps.

The answers above missing one important point -> efficiency.

There is no need to allocate a string in memory, especially if your JSON is big. Streams can do much better then strings:

// Read the response as stream
var stream = await response.Content.ReadAsStreamAsync();

// Use the next method for deserialization
T DeserializeJsonFromStream<T>(Stream stream)
{
    if (stream == null || stream.CanRead == false)
        return default(T);

    using (var sr = new StreamReader(stream))
    using (var jtr = new JsonTextReader(sr))
    {
        var js = new JsonSerializer();
        return js.Deserialize<T>(jtr);
    }
}

P.S.: Code example is bases on Json.NET.
P.S.S.: There are many good articles on this topic, I could recommend to get familiar with the next one.

Assuming that you have done everything correctly. In other words, You're be able to sent your contactID and get back a json.

Let's say your json structure is something like: {"firstname" : "Doe", "lastname" : "foo" "age" : "27"}

One possible way to retrieve the data is as below:

using Newtonsoft.Json;

//after PostAsync()
if (response.IsSuccessStatusCode)
{
    var content = await response.Content.ReadAsStringAsync();
    JObject jContent = (JObject)JsonConvert.DeserializeObject(content);
    string firstName = (string)jContent.GetValue("firstname")
    string lastName = (string)jContent.GetValue("lastname");
    int age = (int)jContent.GetValue("age");
}

Newtonsoft is available on Nuget. you need to install it if you have not done so.

Improved solution

What if your json has many key/values pairs like below:

{ key1 : value1, key2 : value2, key3 : value3, ... key10 : value10}

Then it is not a good idea by doing :

string foo1 = (string)jContent.GetValue("key1");
string foo2 = (string)jContent.GetValue("key2");
//...
string foo10 = (string)jContent.GetValue("key10");

To handle this case, you can create a class:

public class Foo
{
    public string Foo1 {get;set;}
    public string Foo2 {get;set;}
    //...
    public string Foo2 {get;set;}
}

Then, you can do as simple as below:

if (response.IsSuccessStatusCode)
{
    var content = await response.Content.ReadAsStringAsync();
    Foo foo = JsonConvert.DeserializeObject<Foo>(content);
}

The improved solution referecnced from www.newtonsoft.com. Go there and check out other ways of using the library.

Related