Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Mobile / Windows-Phone-7

NZ Post API - JSON

4.67/5 (3 votes)
23 Dec 2012CPOL2 min read 13.9K   64  
Quick and dirty way to use the NZ Post API

Introduction 

Today, I will be discussing using a JSON feed in an application. I have chosen the NZ Post API as it is a very useful API and is well documented. I will be implementing the API on a Windows Phone 7 application, which can be easily migrated up to Windows Phone 8 and Windows RT or migrated down onto a Winforms application.

Background  

NZ Post has an API that allows developers to access tracking information for parcels and CourierPost. This tutorial will be using C# and Newtonsoft - JSON as well as the NZ Post API.

The documentation for the API - NZ POST.

Start a GET Request

C#
private void Start_track_Request()
{
    string licensekey = "";
    string ip = "10.10.10.3";
    string track = trackid.Text;
    string mock = "1"; // "1" is a mock
    string format = "json";
    string url = string.Format(@"http://api.nzpost.co.nz/tracking/track?" + 
        @"license_key={0}&user_ip_address={1}&tracking_code={2}&mock={3}&format={4}",
        licensekey, ip, track, mock, format);
    HttpWebRequest hWebRequest = (HttpWebRequest)HttpWebRequest.Create(url);
    hWebRequest.Method = "GET";
    hWebRequest.BeginGetResponse(Response_Completed, hWebRequest);
}  

NZ Post requires 5 pieces of information from you. It needs your license key to use the service, an IP address, the tracking number, whether the request is a mock or real and finally, what format you want the response in. Above, I have used the string.format method to add this information to the “url” string. Once you have a URL with the specified information, you can send a request to NZ post for a JSON feed using HttpWebRequest. Remember to specify the method as a “GET” request and to invoke “Response_Completed” for the reply JSON string.

The JSON Response

C#
{"AB123456789NZ":{"source":"courier_post",
  "short_description":"Delivered","detail_description":"Delivered 
  on 22/09/09 at 05:40 AM and signed for by \"WCP110 NZPOSTSVSCNTRE\"", 
  "events":[{"flag":"13","description":"Acceptance",
  "date":"21/09/2009","time":"11:29 AM","carrier":
  "CP","location":"AKL North Shore Fleet"},{"flag":"32",
  "description":"Out for Delivery","date":"22/09/2009",
  "time":"04:59 PM","carrier":"CP","location":
  "Hamilton Depot"},{"flag":"22","event_type":"D",
  "description":"Delivered","date":"22/09/2009",
  "time":"05:40 PM","carrier":"CP","location":
  "Wellington Depot","signature_name":"DOMINIQUE HARLEY"}]}}  

The response JSON string will contain all the tracking data related to the tracking number. We now use the “Response_Completed” method to turn the JSON string into usable strings that can be displayed to the user.

JSON to StreamReader

Using HttpWebRequest and HttpWebResponse, we convert the result from the NZ Post servers into a HttpWebResponse so we can parse it into a StreamReader:

C#
public void Response_Completed(IAsyncResult result)
{
   HttpWebRequest request = (HttpWebRequest)result.AsyncState;
   HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(result);

Streamreader to JObject

C#
using (StreamReader streamReader = new StreamReader(response.GetResponseStream()))
{
   JObject rootObject = JObject.Load(new JsonTextReader(streamReader));
   Dispatcher.BeginInvoke(() =>

In the above code, we take the HttpWebResponse and parse it into the StreamReader. We then use NewtonSoft JSON to turn the streamReader into a JObject – “rootObject” that can be used to create strings that can be displayed to users. We also have to use Dispatcher.BeginInvoke(() to execute the delegate on the UI thread.

JObject to string

For the final step in the process, we convert the rootObject into single objects that can be converted to strings to display to the user. As seen above, the process for this is to specify the objects you want in the array, and implicitly convert it into a string.

We then apply the strings to the UI.

C#
string source = rootObject[tracknum]["source"].ToString();
string short_des = rootObject[tracknum]["short_description"].ToString();
string detail_des = rootObject[tracknum]["detail_description"].ToString();

textBlock1.Text = "Details Loaded.";
short_description.Text = short_des.ToString();
long_description.Text = detail_des.ToString();

And we're essentially done! I've attached a sample application using this code for you to experiment with (you will need a license from NZ post however). If you have any issues, feel free to contact me. 

Final Notes

  • Don't forget to implement exception handling.
  • You will need to use Newtonsoft JSON, which is a free addon available through the Add-in manager of Visual Studio.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)