Send and Receive JSON, Android + PHP

JSON (JavaScript Object Notation) data

focusing on human-readability and light-weight serialization, JSON is specified using a very small set of symbols, mainly consisting of the curly braces and apostrophes.

For an application this simple, a response string would have worked just as well, but as soon as you start wanting to retrieve multiple records, or store complex data structures, it becomes much easier to simply use JSON, a utility that generally is cross-platform and has a built-in implementation in many languages. Writing a JSON parsing is not a complex project, but the language implementations are generally optimized, well-tested, and already completed.

While XML (eXtensible Markup Language) is widely used and very popular it may not be the best solution for Mobile App. JSON is generally going to be a much lighter weight and faster method for transferring data over wireless networks.

Example 1: sample JSON object, which could be used  to check for a newer version of your app:
{"VersionCode":4,"ChangeLog":"* New Feature 1 ..."}
Pulling down and decoding a JSON object such as this one is a very simple process, which begins with a call to request the data with a method such as the one below.

protected String HTTPGetCall(String WebMethodURL) throws IOException, MalformedURLException 
 { 
 StringBuilder response = new StringBuilder(); 

 //Prepare the URL and the connection 
 URL u = new URL(WebMethodURL); 
 HttpURLConnection conn = (HttpURLConnection) u.openConnection(); 
 if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) 
 { 
 //Get the Stream reader ready 
 BufferedReader input = new BufferedReader(new InputStreamReader(conn.getInputStream()),8192); 
 //Loop through the return data and copy it over to the response object to be processed 
 String line = null; 
 while ((line = input.readLine()) != null) 
 { 
 response.append(line); 
 } 
 input.close(); 
 } 
 return response.toString(); 
 }

This method essentially performs the heavy lifting of making an HTTP Get request and returning a string containing the data returned from the call. This method is actually generic and can be used for requesting JSON data as well as other types including XML. Now that we have a method that can easily download the JSON data, we need to decode it using the JSONObject class as shown below:

//Make the actual request - method displayed above
String result = super.HTTPGetCall(url);
//Parse the result for the JSON data
JSONObject obj = new JSONObject(result);

Using the JSON object we can now pull out VersionCode and ChangeLog as strongly typed values. For the VersionCode we will want to retrieve the value as an Integer and ChangeLog as a String.

int versionCode = obj.getInt("VersionCode");
String changeLog = obj.getString("ChangeLog");

Despite being a simple example, it does illustrate the principals involved in downloading JSON and extracting usable data. Working with JSON is not limited to primitive types either; it does include support for JSONArrays, which are a necessity for working with lists of data.

Example 2:

You are creating an Android app and want to read data from a MySQL database and send data. We will create a Web Service in PHP, read from the MySQL database, and let the Android connect with the Web Service and send data, and the Web Service will save it and another Web Service will read data from MySQL and send it to the Android app.

 back-end script

that can successfully receive a JSON request, turn that request into something meaningful, and spit it back out again as a response.

Setup a single request and a single response data-type:

Request

    • action – Parameter specifying which action the server is to perform

Response

    • success – Parameter specifying whether the request was successful or failed due to unforeseen complications (database issues, file access, etc).
    • quote – An array of potentially multiple random quotes, for now it will only return one member, but this could be extended to support multiple quotes. Each quote member will consist of a quote field, and an author field, containing the quote and the author, respectively.

e.g. a typical request and response:

Request: {"action":"getQuote"}
Response: {"success":true,"quote":[{"quote":"I want to know God's thoughts... the rest are details.","author":"Albert Einstein"}]}

JSon is more structured than the typical name-value pair passing done in the absence of any formal specification

 to wrap the JSON data around a POST request

POST requests are generally just blobs of name-value text data. I will be storing the JSON data in a parameter called payload, while I’ll create an additional parameter called APIKey as a first line of defense against typical DOS attacks and other unwanted execution of my script.

About these ads

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

生活在西班牙

自己动手丰衣足食

BlueAsteroid

Just another WordPress.com site

Jing's Blog

Just another WordPress.com site

Start from here......

我的心情魔方

天才遠私廚

希望能做一個分享各種資訊的好地方

语义噪声

西瓜大丸子汤的博客

Augmented Reality Blog

An augmented point of view

笑对人生,傲立寰宇

Just another WordPress.com site

Where On Earth Is Waldo?

A Project By Melanie Coles

the Serious Computer Vision Blog

A blog about computer vision and serious stuff

Cauthy's Blog

paper review...

Cornell Computer Vision Seminar Blog

Blog for CS 7670 - Special Topics in Computer Vision

datarazzi

Life through nerd-colored glasses

Luciana Haill

Augmenting Consciousness with EEG

槑烎

1,2,∞

Paul Tennent

Wanderings in the Blogosphere

turn off the lights, please

A bunch of random, thinned and stateless thoughts around the Web

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: