这就是我在 jasper 中处理 json 数组的方式
假设我想报告以下数组。
[
{"name":"Jerry", "value":"Jesus"},
{"name":"Gideon", "value": "Loves"},
{"name":"Eva", "value": "You"}
]
设计报告时,请确保将字段命名为与 json 字段名称完全相同的名称。所以在设计器中我会添加两个字段,分别称为name和value。您甚至可以根据需要向报表设计器添加任意数量的参数。对于这个例子,我将在 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/我能够让它与设置一起工作java for jasper 使用 gradle 构建工具。