Communicating PHP with Android Java using JSON

When you have several variables (data) which you would send to Android using regular text on HTTP, then JSON would become an alternative format to XML. Android has it’s own JSON parser class which able to convert text on JSON format into a JSON Object. Since version 5.2.0, PHP has it’s built in json_encode() and json_decode() function to convert an array into json string and vice versa.

Here is an example on how to encode an array into JSON string:

<?php
  $arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
  echo json_encode($arr);
?>

The above example will output the following text:

{"a":1,"b":2,"c":3,"d":4,"e":5}

More information on json_encode() function on PHP can be seen here.

In Android, after putting the JSON string into a variable (e.g. from a HTTP Request), you may directly convert it into a JSONObject object. For example:

String JSONString = this.getResponseString();
if(JSONString != null) {
	JSONObject jObj;
	try {
		jObj = new JSONObject(JSONString);
		return jObj;
	} catch (JSONException e) {
		this.error = e.getMessage();
		e.printStackTrace();
	}
}

jObj is the JSONObject object in which the decoded JSON string is in from JSONString variable. if JSONString is unable to be decoded, then a JSONException will be raised. Otherwise the object variables (data) inside jObj object is ready to be used on your Android application.

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