In order to demonstrate what we can do with JSON we need a server to query. I found this website which is set up exactly for our purpose. We will use the date and time service and we will need to send our request to this address: http://date.jsontest.com.
The server will respond with the information requested in JSON format, like so:
1 2 3 4 5 | { "time": "03:53:25 AM", "milliseconds_since_epoch": 1362196405309, "date": "03-02-2013" } |
This is pretty much what objects look like in JavaScript. Also, we can visualize this like an HashMap, where, for example, on line 2, the key "time" will return the value "03:53:25 AM".
In our application we simply want to display the time and the date using two TextViews.
All can be achieved with a single class which, following our last tutorial, will extend AsyncTask once again in order to make our request asynchronous
Let's have a look at the class itself, called JSONDownloader:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 | public class JSONDownloader extends AsyncTask<String, Void, String> { Activity act; TextView time,date; public JSONDownloader(Activity act) { this.act = act; time = (TextView) act.findViewById(R.id.textTime); date = (TextView) act.findViewById(R.id.textDate); } @Override protected void onPostExecute(String s) { super.onPostExecute(s); try { JSONObject j = new JSONObject(s); time.setText(j.get("time").toString()); date.setText(j.get("date").toString()); } catch (JSONException e) { e.printStackTrace(); } } @Override protected String doInBackground(String... params) { String result = ""; try { URL url = new URL(params[0]); HttpURLConnection connection; connection = (HttpURLConnection) url.openConnection(); InputStream in = connection.getInputStream(); InputStreamReader reader = new InputStreamReader(in); int data = reader.read(); while(data!=-1) { char c = (char)data; result += c; data = reader.read(); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return result; } } |
First thing first, the constructor. We simply pass in the Activity which we use to get our TextViews references.
In the doInBackground method we send the request: first we create an URL object passing the first paramter of our var args which is going to be the address I linked above, you will see it in a minute in the MainActivity class. Calling the method open() form this object we get our HttpURLConnection object, which is used to get our InputStream and, consequently, our InputStreamReader. All the data collected is ultimately put into a String variable, called result which is the value returned by the function.
Our String now contains the information we wanted in JSON, so we need to find a way to extract what we need which, in our case, is a String containing the time information and one for the date.
Thankfully for us, Java has a very easy way to work with JSON with a built-in class of the same name.
As you can see in the onPostExecute method, we can create JSON object and pass in the constructor the String we just filled with the information.
Once we have the JSON object ready we can extrapolate values using the method get(..). You can see on lines 21 and 22 that, in order to get our date and time, we call that method passing in the keys "time" and "date", which are the 2 keys that need to be used to get our data as we saw on the website. At this point we are returned String values which we can place as texts in our TextViews.
Finally, in the MainActivity, we create the class object and execute the task:
1 2 3 4 5 6 7 8 9 10 11 12 | public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); JSONDownloader d = new JSONDownloader(this); d.execute("http://date.jsontest.com/"); } } |
Conclusion
A very simple and effective example on how to use JSON to obtain data from the internet. We can of course send data as well and that is something that I will perhaps show later. JSON is rapidly becoming the standard used to send data across different systems and you can already find many websites that have APIs and they offer a wide variety of services (like news, weather information and more) that you can use in your app simply by sending http request and use JSON to process the data.