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.

17 Replies to “Communicating PHP with Android Java using JSON”

  1. Thank you very much Mr. Aryo Pinandito, a very helpful article. The writing is very detailed and also using vocabulary that is easily understood by beginners like me, became more eager to learn hehe.

  2. ok, it is good, i like them.Thank you very much Mr. Aryo Pinandito, a very helpful article. The writing is very detailed and also using vocabulary that is easily understood by beginners like me, became more eager to learn hehe.

  3. Our God reigns victorious. We are not defeated. The brokenness will not be forever. And so we continue to move forward in faith, allowing ourselves to be used of God, because He can make a difference and bring cleansing and healing to this broken and messed up world one drop at a time.

Leave a Reply

Your email address will not be published. Required fields are marked *

*