Home » » Communicating PHP with Android Java using JSON

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:


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.

Thanks for reading Communicating PHP with Android Java using JSON

« Previous
« Prev Post
Next »
Next Post »

0 komentar:

Post a Comment