Tutorial #85: Fetch data from WordPress posts using JSON API

Hello everyone!

I recently helped a friend of mine setup his own blog using WordPress. It feels great to see people slowly moving towards blogging. WordPress is one of the popular content management systems out there that make blogging a lot easier. It provides the ability to not only assign multiple categories to articles but also support for tagging of posts and articles.

As a developer, one can use the JSON API to fetch the data related to a post published on WordPress. The API is basically a WordPress plugin that allows you to retrieve and manipulate WordPress content using HTTP requests. For example, one could fetch all posts tagged “java” by executing an HTTP GET request to the following URL.

http://www.example.org/?json=get_tag_posts&tag_slug=java

Through this post, we will learn how to fetch data from WordPress posts using the JSON API.

Pre-requisites: Eclipse IDE, Android SDK

Step 1: Installing JSON API plugin

Here I assume you already have a live WordPress website. Login to your WordPress account and install the JSON API plugin. Once installed, activate the plugin.

Step 2: Fetch data from WordPress post

Launch Eclipse IDE and create a new Android application project called AndroidWordPressDemo with package name com.app.wordpress. Create a new Activity class called FetchDataActivity and add the following code!

FetchDataActivity.java

package com.app.wordpress;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class FetchDataActivity extends Activity {

	private Button btnSubmit;
	private final static String URL = "http://www.karanbalkar.com/api/get_tag_posts/?tag_slug=sdcard";
	private TextView tvPostCount, tvPostTitle, tvPostUrl;


	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		tvPostCount = (TextView)findViewById(R.id.txtPostCount);
		tvPostTitle = (TextView)findViewById(R.id.txtPostTitle);
		tvPostUrl = (TextView)findViewById(R.id.txtPostUrl);


		btnSubmit = (Button)findViewById(R.id.btnSubmit);
		btnSubmit.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				new FetchDataTask().execute(URL);
			}
		});

	}

	private class FetchDataTask extends AsyncTask<String, Void, String>{

		@Override
		protected String doInBackground(String... params) {
			// TODO Auto-generated method stub
			InputStream inputStream = null;
			String result= null;
			HttpClient client = new DefaultHttpClient();
			HttpGet httpGet = new HttpGet(params[0]);

			try {

				HttpResponse response = client.execute(httpGet);
				inputStream = response.getEntity().getContent();

				// convert inputstream to string
				if(inputStream != null){
					result = convertInputStreamToString(inputStream);
					Log.i("App", "Data received:" +result);

				}
				else
					result = "Failed to fetch data";

				return result;

			} catch (ClientProtocolException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}

			return null;
		}

		@Override
		protected void onPostExecute(String dataFetched) {
			//parse the JSON data and then display
			parseJSON(dataFetched);
		}


		private String convertInputStreamToString(InputStream inputStream) throws IOException{
			BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
			String line = "";
			String result = "";
			while((line = bufferedReader.readLine()) != null)
				result += line;

			inputStream.close();
			return result;

		}

		private void parseJSON(String data){

			try{

				JSONObject jsonResponse = new JSONObject(data);
				JSONArray jsonMainNode = jsonResponse.optJSONArray("posts");
				int postCount = Integer.parseInt(jsonResponse.getString("count"));

				int jsonArrLength = jsonMainNode.length();  

				for(int i=0; i < jsonArrLength; i++) {
		
					JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
					String postTitle = jsonChildNode.getString("slug");
					String postUrl = jsonChildNode.getString("url");
				
					tvPostCount.setText("Number of posts:" +postCount);
					tvPostTitle.setText("Page title:" +postTitle);
					tvPostUrl.setText("Page URL:" +postUrl);
				}
				
			}catch(Exception e){
				Log.i("App", "Error parsing data" +e.getMessage());

			}
		}
	}

}

activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="${relativePackage}.${activityClass}" >

    <TextView
        android:id="@+id/txtView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />

    <Button
        android:id="@+id/btnSubmit"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/txtView1"
        android:text="@string/fetchData" />

    <TextView
        android:id="@+id/txtPostTitle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/btnSubmit" />

    <TextView
        android:id="@+id/txtPostCount"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/txtPostTitle" />

    <TextView
        android:id="@+id/txtPostUrl"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/txtPostCount" />

</RelativeLayout>

Note: Make sure you add the below INTERNET permission in your AndroidManifest.xml file.

 <uses-permission android:name="android.permission.INTERNET" />

Finally, save all changes. Make sure no errors are present and run the application on an Android device. Click on the button to view the corresponding output! πŸ™‚

output

That’s it for this tutorial. Hope it helps. Stay tuned for more! πŸ™‚

Populate Highcharts with JSON data using jQuery

Hello everyone!

Graphs and charts help make information easier to visualize. Developers can display charts for better analysis and understanding. Highcharts help develop interactive JavaScript charts for web pages. It is basically a charting library written in pure JavaScript, offering an easy way of adding charts to your web site or web application.

Through this post, we will learn how to populate and display a bar chart dynamically using JSON data received via a RESTful web service.

Pre-requisites: Eclipse IDE, Notepad , Apache Tomcat 7

Step 1: Create dynamic web project

Let’s first create a web project that exposes a web service to send JSON data. Launch Eclipse IDE and create a Dynamic Web Project called TestHttpJson. Create a new Service class called DataService and add the following code!

DataService.java

package com.example;

import java.util.HashMap;
import java.util.Map;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response;
import org.json.JSONArray;
import org.json.JSONObject;

@Path("/rest")
public class DataService {

	@Context org.jboss.resteasy.spi.HttpResponse response;
	@Path("/json")
	@Produces("application/json")
	@GET
	public Response getJSONData() {

		Map<String, String> data1 = new HashMap<String,String>();
		data1.put( "key", "Computers");
		data1.put( "value","114");

		Map<String, Object> data2 = new HashMap<String, Object>();
		data2.put( "key", "Electronics");
		data2.put( "value","214");

		Map<String, Object> data3 = new HashMap<String, Object>();
		data3.put( "key", "Mechanical");
		data3.put( "value","514");

		JSONObject json1 = new JSONObject(data1);
		JSONObject json2 = new JSONObject(data2);
		JSONObject json3 = new JSONObject(data3);

		JSONArray array = new JSONArray();
		array.put(json1);
		array.put(json2);
		array.put(json3);

		JSONObject finalObject = new JSONObject();
		finalObject.put("student_data", array);

		response.getOutputHeaders().putSingle("Access-Control-Allow-Origin", "*");
		return Response.status(200).entity(finalObject.toString()).build();
	}

}

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://java.sun.com/xml/ns/javaee"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
	id="WebApp_ID" version="3.0">
	<display-name>TestHttpJson</display-name>
	<welcome-file-list>
		<welcome-file>index.html</welcome-file>
		<welcome-file>index.htm</welcome-file>
		<welcome-file>index.jsp</welcome-file>
		<welcome-file>default.html</welcome-file>
		<welcome-file>default.htm</welcome-file>
		<welcome-file>default.jsp</welcome-file>
	</welcome-file-list>

	<!-- Auto scan REST service -->
	<context-param>
		<param-name>resteasy.scan</param-name>
		<param-value>true</param-value>
	</context-param>

	<context-param>
		<param-name>resteasy.servlet.mapping.prefix</param-name>
		<param-value>/</param-value>
	</context-param>

	<listener>
		<listener-class>
			org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap</listener-class>
	</listener>

	<servlet>
		<servlet-name>resteasy-servlet</servlet-name>
		<servlet-class>
			org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher</servlet-class>
	</servlet>

	<servlet-mapping>
		<servlet-name>resteasy-servlet</servlet-name>
		<url-pattern>/*</url-pattern>
	</servlet-mapping>

</web-app>

Note: You need to include the REST API specific jars before running the application. Please refer this post for more information.

Now, run the project on the Tomcat server and enter the following URL,

http://localhost:8080/TestHttpJson/rest/json

You should see the JSON data in the browser page.

output_3

Step 2: Create HTML page

Next, we need to use HighCharts API to create our bar chart using JSON data of the web service. The jQuery.getJSON() method helps load JSON-encoded data from the server using a GET HTTP request.

index.html

<!DOCTYPE html>

<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8" />
    <title>College student data</title>
    <script type="text/javascript" src="js/jquery-1.9.1.js"></script>
    <script type="text/javascript" src="js/highcharts.js"></script>
    <script type="text/javascript">
        $(function () {
         
				var processed_json = new Array();	
				$.getJSON('http://localhost:8080/TestHttpJson/rest/json', function(data) {
		
					// Populate series
					for (i = 0; i < data.student_data.length; i++){
						processed_json.push([data.student_data[i].key, parseInt(data.student_data[i].value)]);
					}
				
				    // draw chart
					$('#container').highcharts({
					chart: {
						type: "column"
					},
					title: {
						text: "Student data"
					},
					xAxis: {
						allowDecimals: false,
						title: {
							text: "Branch of studies"
						}
					},
					yAxis: {
						title: {
							text: "Number of students"
						}
					},
					series: [{
						data: processed_json
					}]
				});	
			});
		});
    </script>
</head>
<body>
    <div id="container" style="height: 400px"></div>
</body>
</html>

Finally, open the above HTML page in the browser. If no errors occur, then you should see the following output!

output_1

output_2

In addition, one can also use the various chart types and options for better customization. Hope this helps! Thanks for visiting! πŸ™‚

Parsing JSON using Qt 5 framework

Hello friends!

In one of my previous posts, we had seen how to send a HTTP request using Qt. The response we got then was a JSON string. JSON is a subset of the object literal notation of JavaScript. It is basically a lightweight data-interchange format making it easy for humans to read and write. A JSON is build on two structures namely,

  • A collection of name/value pairs. In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list or associative array.

  • An ordered list of values. In most languages, this is realized as an array, vector, list or sequence.

  • A sample valid JSON looks as follows!

    {"success":"true","controls":[{"controlID":"1","type":"TEXTBOX"},{"controlID":"4","type":"CHECKBOX"}]}
    

    An object is an un-ordered set of name/value pairs. An object begins with { (left brace) and ends with } (right brace). Each name is followed by : (colon) and the name/value pairs are separated by , (comma). On the other hand, an array is an ordered collection of values. An array begins with [ (left bracket) and ends with ] (right bracket). Values are separated by , (comma).

    Through this post, we will learn to parse JSON using Qt 5.

    Pre-requisites: Qt Creator, MinGW compiler (Windows – 64 bit)

    Launch Qt Creator and create a new Qt console application project called TestJsonParsing. Choose the default Desktop kit.

    Now, let’s add our JSON parser code in the main.cpp file as follows!

    main.cpp

    #include <QCoreApplication>
    #include <QDebug>
    #include <QApplication>
    #include <QtWebKitWidgets/QWebFrame>
    #include <QtWebKitWidgets/QWebPage>
    #include <QtWebKitWidgets/QWebView>
    #include <QNetworkAccessManager>
    #include <QNetworkRequest>
    #include <QNetworkReply>
    #include <QUrl>
    #include <QUrlQuery>
    #include <QWebSettings>
    #include <QVariant>
    #include <QJsonValue>
    #include <QJsonDocument>
    #include <QJsonObject>
    #include <QVariantMap>
    #include <QJsonArray>
    
    void sendRequest();
    
    int main(int argc, char *argv[])
    {
        QCoreApplication a(argc, argv);
        sendRequest();
        return a.exec();
    }
    
    void sendRequest() {
    
        // create custom temporary event loop on stack
        QEventLoop eventLoop;
    
        // "quit()" the event-loop, when the network request "finished()"
        QNetworkAccessManager mgr;
        QObject::connect(&mgr, SIGNAL(finished(QNetworkReply*)), &eventLoop, SLOT(quit()));
    
        // the HTTP request
        QNetworkRequest req( QUrl( QString("http://time.jsontest.com/") ) );
        QNetworkReply *reply = mgr.get(req);
        eventLoop.exec(); // blocks stack until "finished()" has been called
    
        if (reply->error() == QNetworkReply::NoError) {
    
            QString strReply = (QString)reply->readAll();
    
            //parse json
            qDebug() << "Response:" << strReply;
            QJsonDocument jsonResponse = QJsonDocument::fromJson(strReply.toUtf8());
    
            QJsonObject jsonObj = jsonResponse.object();
    
            qDebug() << "Time:" << jsonObj["time"].toString();
            qDebug() << "Date:" << jsonObj["date"].toString();
    
            delete reply;
        }
        else {
            //failure
            qDebug() << "Failure" <<reply->errorString();
            delete reply;
        }
    }
    

    .pro file

    QT       += core
    QT       -= gui
    QT       += network
    QT       += webkit webkitwidgets
    
    TARGET = TestJsonParsing
    CONFIG   += console
    CONFIG   -= app_bundle
    
    TEMPLATE = app
    
    SOURCES += main.cpp
    
    

    Save all changes. Build and run the application. If no errors are present then you should see the following output!

    qt_json_parsing

    That’s it then for this useful Qt tip. Hope it helps! πŸ™‚

    Reference: QJsonDocument, QJsonArray