这就是我在 jasper 中处理 json 数组的方式
假设我想报告以下数组。
[
{"name":"Jerry", "value":"Jesus"},
{"name":"Gideon", "value": "Loves"},
{"name":"Eva", "value": "You"}
]
设计报表时,请确保将字段命名为与 json 字段名称完全相同的名称。因此,在设计器中,我会添加两个称为名称和值的字段。您甚至可以根据需要向报表设计器中添加任意数量的参数。对于此示例,我将在 Jasper Studio 中添加一个名为 title 的参数。
现在,这是 java 代码,它将基于此测试数组创建 jasper 报告。我会在代码中对json数据进行硬编码,但您可以从文件或您认为最好的任何内容加载。我注释了代码来解释正在发生的事情。
import net.sf.jasperreports.engine.export.JRHtmlExporterParameter;
import net.sf.jasperreports.engine.export.JRXlsExporterParameter;
import net.sf.jasperreports.engine.export.JRHtmlExporter;
import net.sf.jasperreports.engine.export.JRXlsExporter;
import net.sf.jasperreports.engine.data.JsonDataSource;
import net.sf.jasperreports.engine.JRExporterParameter;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.util.JRLoader;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperPrint;
import org.apache.commons.codec.binary.Base64;
import java.util.HashMap;
import java.util.Locale;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.io.*;
//Class Name. This must match the class name you put in your build.gradle file
public class JasperPDFExample {
public static void main(String[] args) {
try {
try {
//Our json object. This can be loaded from file
String rawJsonData = "[{\"name\":\"Jerry\", \"value\":\"Jesus\"},"
+ "{\"name\":\"Gideon\", \"value\": \"Loves\"},"
+ "{\"name\":\"Eva\", \"value\": \"You\"}"
+ "]";
//Load compiled jasper report that we created on first section.
JasperReport report = (JasperReport) JRLoader.loadObject(new File("/home/jerry/Sample.jasper"));
//Convert json string to byte array.
ByteArrayInputStream jsonDataStream = new ByteArrayInputStream(rawJsonData.getBytes());
//Create json datasource from json stream
JsonDataSource ds = new JsonDataSource(jsonDataStream);
//Create HashMap to add report parameters
Map parameters = new HashMap();
//Add title parameter. Make sure the key is same name as what you named the parameter in jasper report.
parameters.put("title", "Jasper PDF Example");
//Create Jasper Print object passing report, parameter json data source.
JasperPrint jasperPrint = JasperFillManager.fillReport(report, parameters, ds);
//Export and save pdf to file
JasperExportManager.exportReportToPdfFile(jasperPrint,"/home/jerry/jasperpdfexample.pdf");
} catch (JRException ex) {
ex.printStackTrace();
throw new RuntimeException(ex);
} catch (Exception ex) {
ex.printStackTrace();
throw new RuntimeException(ex);
}
} catch (Exception ex) {
ex.printStackTrace();
throw new RuntimeException(ex);
}
}
}
多亏了 https://mis.io/pub/how-to-create-a-jasper-pdf-report-from-a-json-datasource-in-java/ 我能够让它与使用gradle构建工具为jasper设置java一起工作。