Looking forward on improving the
GPS phone tutorial from last time, will be adding our pushpins and markers from a
JSON(JavaScript Object Notation) array, so the first step will be to learn how to parse our array, this blog post will be short because this is not our main goal.
I will be using a
PHP and
WAMP server to locally host my the json data.
Requirements:
- wamp server download HERE
- Visual studio
- Newtonsoft.json.dll download HERE or you can install directly to your project in visual studio follow these steps:
- click the project tab in visual studio
- click manage NuGet packages
- wait for it to load and select Json.NET click install, this will allow us import the Newtonsoft.json.dll library.
Let us begin by setting up our JSON data from our database through PHP. I am not going to explain the PHP code but the comments within the code should be really helpful.
I won't be going into database configuration either, if need help on that visit this website
Kiwixcompo
If you can recall GPS phone was about finding restaurants on the map and call for a reservation or place an order. Our json encoded data has to fit this need.
This is the PHP script to encode our data.
This our db_connect.php file with our connection variables
<?php
define('DB_USER', "root");
define('DB_PASSWORD', "");
define('DB_DATABASE', "jsontest");
define('DB_SERVER', "localhost");
?>
This is our db_kinnect.php file which checks out database connection status and connects us to the database
<?php
/**
* A class file to connect to database
*/
class DB_CONNECT {
// constructor
function __construct() {
// connecting to database
$this->connect();
}
// destructor
function __destruct() {
// closing db connection
$this->close();
}
/**
* Function to connect with database
*/
function connect() {
// import database connection variables
require_once __DIR__ . '/db_connect.php';
// Connecting to mysql database
$con = mysql_connect(DB_SERVER, DB_USER, DB_PASSWORD) or die(mysql_error());
// Selecing database
$db = mysql_select_db(DB_DATABASE) or die(mysql_error()) or die(mysql_error());
// returning connection cursor
return $con;
}
/**
* Function to close db connection
*/
function close() {
// closing db connection
mysql_close();
}
}
?>
This is the file that wil spit out our JSON from the database for our mobile consumption
<?php
/*
* Following code will list all the Restaurants
*/
// array for JSON response
$response = array();
// include db connect class
require_once __DIR__ . '/db_kinect.php';
// connecting to db
$db = new DB_CONNECT();
restaurants") or die(mysql_error());
// check for empty result
if (mysql_num_rows($result) > 0) {
// looping through all results
// restaurants node
$response["restaurants"] = array();
while ($row = mysql_fetch_array($result)) {
// temp user array
$restaurants_array = array();
$restaurants_array["pid"] = $row["pid"];
$restaurants_array["longitude"] = $row["longitude"];
$restaurants_array["latitude"] = $row["latitude"];
$restaurants_array["created_at"] = $row["created_at"];
$restaurants_array["updated_at"] = $row["updated_at"];
// push single restaurant into final response array
array_push($response["restaurants"], $restaurants_array);
}
// success
$response["success"] = 1;
// echoing JSON response
echo json_encode($response);
} else {
// no location found
$response["success"] = 0;
$response["message"] = "No location found";
// echo no users JSON
echo json_encode($response);
}
?>
The php code above should give us the required json we desire. see out put below
{"restaurants":[{"pid":"1","longitude":"46.8799000000","latitude":"35.8779000000","created_at":"2014-02-09 17:24:49","updated_at":"0000-00-00 00:00:00"},{"pid":"2","longitude":"25.5858660000","latitude":"62.8585850000","created_at":"2014-02-09 19:51:14","updated_at":"0000-00-00 00:00:00"},{"pid":"3","longitude":"9.3241082570","latitude":"9.1728899140","created_at":"2014-02-11 23:52:43","updated_at":"0000-00-00 00:00:00"},{"pid":"4","longitude":"8.8359202210","latitude":"7.4974748750","created_at":"2014-02-11 23:52:43","updated_at":"0000-00-00 00:00:00"}],"success":1}
That is all the PHP-ing we will be doing (thank God);
copy the output json and goto
Json2csharp.com paste the json output and click
generate button you will get two csharp classes that looks like these ones below
public class Restaurant
{
public string pid { get; set; }
public string longitude { get; set; }
public string latitude { get; set; }
public string created_at { get; set; }
public string updated_at { get; set; }
}
public class RootObject
{
public List restaurants { get; set; }
public int success { get; set; }
}
With that done we are ready start coding our windows phone app
create a windows phone app and add a
ListBox as shown below
<ListBox HorizontalAlignment="Left" Name="dList" Height="391" Margin="10,43,0,0" VerticalAlignment="Top" Width="436">
That is all we need to add next we have to switch over to our C# file and start the real work, first we have to add our Newtonsoft.Json
using Newtonsoft.Json;
We then setup our WebClient call to our JSON API as follows
//Web client call to JSON API
WebClient wClient = new WebClient();
wClient.DownloadStringCompleted +=new DownloadStringCompletedEventHandler(wClient_Downloaded);
wClient.DownloadStringAsync(new Uri("http://localhost/Police/get_all_locs.php"));
Paste the Restaurant and RootObject classes we got from json2csharp into the MainPage class; the next thing we have to is implement our DownLoadStringCompleted event argument in this case wClient_Downloaded
public void wClient_Downloaded(object sender, DownloadStringCompletedEventArgs e)
{
try
{
var rootObj = JsonConvert.DeserializeObject(e.Result);
foreach(var stationz in rootObj.location)
{
dList.Items.Add(stationz.station_name);
dList.Items.Add(stationz.longitude);
dList.Items.Add(stationz.latitude);
}
}
catch (Exception ex)
{
MessageBox.Show("Error>>>> "+ex);
}
}
You will notice will notice we had put the commands within the try, catch blocks to handle any exception and that is all you need to consume JSON.
Full C# code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using Microsoft.Phone.Tasks;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.Device.Location;
using Microsoft.Phone.Controls.Maps;
using System.Windows.Media.Imaging;
using System.Windows.Controls.Primitives;
using System.ComponentModel;
using System.Collections;
using Newtonsoft.Json;
namespace PhoneApp4
{
public partial class MainPage : PhoneApplicationPage
{
// Constructor
public MainPage()
{
InitializeComponent();
//Web client call to JSON API
WebClient wClient = new WebClient();
wClient.DownloadStringCompleted +=new DownloadStringCompletedEventHandler(wClient_Downloaded);
wClient.DownloadStringAsync(new Uri("http://localhost/Police/get_all_locs.php"));
}
public void wClient_Downloaded(object sender, DownloadStringCompletedEventArgs e)
{
try
{
var rootObj = JsonConvert.DeserializeObject(e.Result);
foreach(var stationz in rootObj.location)
{
dList.Items.Add(stationz.station_name);
dList.Items.Add(stationz.longitude);
dList.Items.Add(stationz.latitude);
}
}
catch (Exception ex)
{
MessageBox.Show("Error>>>> "+ex);
}
}
public class Location
{
public string pid { get; set; }
public string longitude { get; set; }
public string latitude { get; set; }
public string created_at { get; set; }
public string updated_at { get; set; }
public string station_name { get; set; }
}
public class RootObject
{
public List location { get; set; }
public int success { get; set; }
}
}
}
OUTPUT: