How to populate a dataTable from a JSON file

How to use natively JSON data into a JSF dataTable ? When using Primefaces you have more than one option to do it!

The JSF dataTable tag is used to display data on JSF view pages. The data bound table components are responsible for displaying the relational data in a tabular format. typically a dataTable is backed by a List of java Objects which are filled from a source. As you can imagine, by parsing an external resource of file you can display anything you like in your dataTable.

Primefaces, however, ships with two built-in solutions which are perfectly fit for displaying data in JSON format.

Use JSONArray and JSONObject

The first solution we will discuss is a pure Java solution which uses some classes in the package org.primefaces.json that can be added directly into the dataTable’s list. Let’s see an example:

package com.mastertheboss;

import java.util.ArrayList;
import java.util.List;

import javax.faces.bean.ApplicationScoped;
import javax.faces.bean.ManagedBean;

import org.primefaces.json.JSONArray;
import org.primefaces.json.JSONObject;

@ManagedBean(name = "jsonService")
@ApplicationScoped
public class MyJsonService {

    public List getData() throws Exception {
        String data = "  [{\n" + 
                "    \"nm\": \"Harold II\",\n" + 
                "    \"cty\": \"United Kingdom\",\n" + 
                "    \"hse\": \"House of Wessex\",\n" + 
                "    \"yrs\": \"1066\"\n" + 
                "  },\n" + 
                "  {\n" + 
                "    \"nm\": \"William I\",\n" + 
                "    \"cty\": \"United Kingdom\",\n" + 
                "    \"hse\": \"House of Normandy\",\n" + 
                "    \"yrs\": \"1066-1087\"\n" + 
                "  },\n" + 
                "  {\n" + 
                "    \"nm\": \"William II\",\n" + 
                "    \"cty\": \"United Kingdom\",\n" + 
                "    \"hse\": \"House of Normandy\",\n" + 
                "    \"yrs\": \"1087-1100\"\n" + 
                "  },\n" + 
                "  {\n" + 
                "    \"nm\": \"Henry I\",\n" + 
                "    \"cty\": \"United Kingdom\",\n" + 
                "    \"hse\": \"House of Normandy\",\n" + 
                "    \"yrs\": \"1100-1135\"\n" + 
                "  },\n" + 
                "  {\n" + 
                "    \"nm\": \"Stephen\",\n" + 
                "    \"cty\": \"United Kingdom\",\n" + 
                "    \"hse\": \"House of Blois\",\n" + 
                "    \"yrs\": \"1135-1154\"\n" + 
                "  }]";

        List monarchList = new ArrayList<>();
        JSONArray jsonArray = new JSONArray(data);
        for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject json = jsonArray.getJSONObject(i);  
            monarchList.add(new Monarch(json.getString("nm"), json.getString("cty"), json.getString("hse"), json.getString("yrs")));
        }

        return monarchList;
    }

}

So in this bean we have statically created a JSON String which is an array of items. We have therefore created a JSONArray from that String and extracted the JSONObject creating a Java Bean for each entry. The Java Bean class (Monarch) is added into the List.

This simple Bean class is exposed as a JSF ManagedProperty to your View:

package com.mastertheboss;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.ViewScoped;

@ManagedBean(name = "jsonView")
@ViewScoped

public class MyJsonView implements Serializable {

    private List monarchList = new ArrayList<>();

    @ManagedProperty("#{jsonService}")
    private MyJsonService service;

    @PostConstruct
    public void init() {
        try {
            monarchList = service.getData();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public List getMonarchList() {
        return monarchList;
    }

    public void setMonarchList(ArrayList list) {
        this.monarchList = list;
    }

    public void setService(MyJsonService service) {
        this.service = service;
    }
}

That’s all. For the sake of completeness, we will include also the Java Bean class:

package com.mastertheboss;

public class Monarch {
    String name;
    String city;
    String house;
    String years;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Monarch(String name, String city, String house, String years) {
        super();
        this.name = name;
        this.city = city;
        this.house = house;
        this.years = years;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public String getHouse() {
        return house;
    }

    public void setHouse(String house) {
        this.house = house;
    }

    public String getYears() {
        return years;
    }

    public void setYears(String years) {
        this.years = years;
    }
}

The index.xhtml page, will display your dataTable’s List of Monarch objects:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
          xmlns:h="http://xmlns.jcp.org/jsf/html"
          xmlns:p="http://primefaces.org/ui">
        <h:head>
            <title>JSON Datatable</title>
        </h:head>
        <h:body>
            <h:form>
                <p:dataTable var="data" value="#{jsonView.monarchList}">
                    <p:column headerText="Name" sortBy="#{data.name}">
                        <h:outputText value="#{data.name}" />
                    </p:column>
                    <p:column headerText="House" sortBy="#{data.house}">
                        <h:outputText value="#{data.house}" />
                    </p:column>
                    <p:column headerText="City" sortBy="#{data.city}">
                        <h:outputText value="#{data.city}" />
                    </p:column>
                    <p:column headerText="Years" sortBy="#{data.years}">
                        <h:outputText value="#{data.years}" />
                    </p:column>                                        
                </p:dataTable>
            </h:form>
        </h:body>
    </html>

Here is your application once deployed on WildFly:

json primefaces example

You can find the full project here: https://github.com/fmarchioni/mastertheboss/tree/master/web/primefaces/json-datatable

Use Prime UI

Another option is using PrimeUI. PrimeUI is a JavaScript library that spins off from PrimeFaces and consists of a set of javascript widgets to create rich UIs easily. So basically it’s a decoupling from the standard widgets based on (PrimeFaces + JSF) and creating a pure javascript library to make Primefaces widgets available to any framework. These widgets are implemented with plain jQuery, designed to work with JSON for data progressing and use client side progressive enhancement to render UIs.

PrimeUI is available for download at: https://github.com/primefaces/primeui/releases . A sample of a dataTable which uses JSON natively is available in the PrimeUI showcase. We will add a simplified example of it here:

<html ng-app>
  <head>
    <link href="development/prime-ui-0.9.5.css" rel="stylesheet">
    <link href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" rel="stylesheet">
    <link href="http://www.primefaces.org/prime-ui/demo/css/aristo/theme.css" rel="stylesheet">
    <link href="http://www.primefaces.org/prime-ui/demo/css/sh.css" rel="stylesheet">
    <link href="http://www.primefaces.org/css/all.css" rel="stylesheet">
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.js"></script>
    <script type="text/javascript" src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
    <script type="text/javascript" src="development/prime-ui-1.0.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
    <script type="text/javascript">
    $(function() {
        var localData = [
            {'brand': 'Volkswagen', 'year': 2012, 'color': 'White', 'vin': 'dsad231ff'},
            {'brand': 'Audi', 'year': 2011, 'color': 'Black', 'vin': 'gwregre345'},
            {'brand': 'Renault', 'year': 2005, 'color': 'Gray', 'vin': 'h354htr'},
            {'brand': 'BMW', 'year': 2003, 'color': 'Blue', 'vin': 'j6w54qgh'},
            {'brand': 'Mercedes', 'year': 1995, 'color': 'White', 'vin': 'hrtwy34'},
            {'brand': 'Volvo', 'year': 2005, 'color': 'Black', 'vin': 'jejtyj'},
            {'brand': 'Honda', 'year': 2012, 'color': 'Yellow', 'vin': 'g43gr'},
            {'brand': 'Jaguar', 'year': 2013, 'color': 'White', 'vin': 'greg34'},
            {'brand': 'Ford', 'year': 2000, 'color': 'Black', 'vin': 'h54hw5'},
            {'brand': 'Fiat', 'year': 2013, 'color': 'Red', 'vin': '245t2s'}
        ];
 
        $('#tbllocal').puidatatable({
            caption: 'Local Datasource',
            columns: [
                {field: 'vin', headerText: 'Vin'},
                {field: 'brand', headerText: 'Brand'},
                {field: 'year', headerText: 'Year'},
                {field: 'color', headerText: 'Color'}
            ],
            datasource: localData
        });
 
         
    });
</script>
  </head>
<body>
  <div id="tbllocal"></div>
 
 
</body>
</html>

As you can see, at the top of our HTML page, we are loading the required jquery, angular and primeui javascript and css. In order to display the datatable into the div named “tbllocal” we have to link the datasource object with a static/remote list of items. In this example, the JSON-like structure has been defined into the variable localData.

Found the article helpful? if so please follow us on Socials