I'm designing a report with a JSON data source (groovy language).
My JSON looks like this:
{
...
"moreIds": [
{
"code": "OB4442735001",
"codScheme": "CLIENT_REF"
},
{
"code": "setr.010",
"codScheme": "INITIAL_SWIFT_TYPE"
},
...
],
...
}
I want to extract the code
value for a given codScheme
value (say "CLIENT_REF") from the moreIds
array.
Initially I tried to extract the value in a field as follows:
<field name="orderClientRef" class="java.lang.String">
<property name="net.sf.jasperreports.json.field.expression" value="moreIds.find{it.codScheme=='CLIENT_REF'}.code"/>
</field>
This doesn't work, it yields an empty value. I tried a bunch of other variations of the expression, but without success.
In the end this is what I did that worked:
I defined a field containing the full moreIds
array:
<field name="moreIds" class="java.lang.Object">
<property name="net.sf.jasperreports.json.field.expression" value="moreIds"/>
</field>
I used the following expression in the text field:
$F{moreIds}.find{it.get("codScheme").textValue()=="CLIENT_REF"}.get("code").textValue()
While it does achieve the goal, I find it less than elegant, and I'd like to know if there is a more elegant way to do this.
I suspect that net.sf.jasperreports.json.field.expression
only wants a field name, and hence it's not happy with a full Groovy expression like that.
It seems like their JSON parser isn't the typical JsonSlurper from Groovy so your syntax you posted would have issues. However, you might simpilfy things (if it's a Groovy Expression) like so:
// working expression
$F{moreIds}.find{it.get("codScheme").textValue()=="CLIENT_REF"}.get("code").textValue()
// get is just the method name for [] operator so you could remove that using:
$F{moreIds).find(it["codScheme"].textValue()=="CLIENT_REF"}["code"]?.textValue()
// and dot notation could work if this is Groovy:
$F{moreIds).find(it.codScheme.textValue()=="CLIENT_REF"}?.code?.textValue()
I added the ?.
operator so if things were null it wouldn't blow up and just gracefully return null.
I think you may look into JSONQL for what you are doing and that might be more elegant in one statement rather than selecting JSON and then applying Groovy Statement.
https://jasperreports.sourceforge.net/sample.reference/jsonqldatasource/README.html