This article helps the reader how to fill a report with data from a JSON data source ( Generating Jasper reports in different formats using a JSON file as a Data Source ). JSON stands for Java Script Object Notation. Suppose that we have a file in the following format. The above file consists of a JSON array. The above JSON array consists of five objects of type students separated by commas. The array notation uses . The JRXML file consists of the following data to generate the report regarding the student details. This JRXML is generated using iReport 5.6.0.
Using the above JSON file data we can fill the JRXML and generate reports in different formats like PDF, HTML, XLS, CSV etc. The Jasper’s API converts the .jrxml into .jasper file and out of the .jasper file a jasperprint object can be made, which can be converted into various formats for printing purposes. Using Jasper’s API requires the following jars in your class path. Add the following dependencies to your pom.xml so that maven will automatically manage the dependencies for you.
Java code to generate the different reports.
The above code consists of an interface JRDataSource, which is implemented by JsonDataSource. The JsonDataSource’s constructor takes a file that consists of the data. For the sake of readability I have used another method which takes 4 arguments – one, the type of file to be generated; two, the JRXML file; three, the data source; four the destination of the file where the file has to be saved.
The above printToFile method takes the data from the data source and fills it in the JRXML and generated the .jasper file which is actually the jasper print object. The jasper print object is used to generate different types of files based on the fileType argument. The above piece of code also demonstrates the use of the new API related to JRXlsExporter and JRCsvExporter, which are actually used to generate excel and csv files respectively.