Search code examples
jsonjasper-reportsjfreechart

How to create JasperReports bar chart using JSON data?


I have a report that is populated with JSON data. I'm now trying to figure out how to structure my JSON so that I can display some data in a pie chart. Can anyone provide an example of how I can use JSON data in a pie chart?


Solution

  • I figured it out! I needed to include a subDataset element defining my queryString:

    <subDataset name="pieDataSet" whenResourceMissingType="Empty" uuid="6e90f719-ceb8-4ecd-9d24-4aa8e07f8e74">
        <parameter name="chartData" class="java.lang.String"/>
    <queryString>
            <![CDATA[chartData]]>
    </queryString>
        <field name="name" class="java.lang.String">
            <fieldDescription><![CDATA[name]]></fieldDescription>
        </field>
        <field name="value" class="java.lang.Integer">
            <fieldDescription><![CDATA[value]]></fieldDescription>
        </field>
    </subDataset>
    

    And then reference the subDataset in the pieChart element using a dataset and datasetRun element like this:

    <pieChart>
        <chart isShowLegend="true" evaluationTime="Report">
            <reportElement x="50" y="0" width="200" height="200" uuid="6c0f07b9-47c5-4a3c-a06a-62b4acda0050"/>
            <box>
                <pen lineWidth="1.0"/>
            </box>
            <chartTitle position="Top">
                <titleExpression><![CDATA["My Pie chart"]]></titleExpression>
            </chartTitle>
            <chartSubtitle/>
            <chartLegend/>
        </chart>
        <pieDataset>
            <dataset>
                <datasetRun subDataset="pieDataSet" uuid="b115e88a-5865-4354-a765-6f629141fef5">
                    <dataSourceExpression><![CDATA[((net.sf.jasperreports.engine.data.JsonDataSource)$P{REPORT_DATA_SOURCE}).subDataSource("chartData")]]></dataSourceExpression>
                </datasetRun>
            </dataset>
            <keyExpression><![CDATA[$F{name}]]></keyExpression>
            <valueExpression><![CDATA[$F{value}]]></valueExpression>
        </pieDataset>
        <piePlot>
            <plot/>
            <itemLabel/>
        </piePlot>
    </pieChart>