2

In my Groovy code, I've got two variables declared:

results is an array of maps. It contains a list of rows returned from a SQL query.

overall is a map. It represents a single row of a separate SQL query.

I want to combine these two variables into one and output the whole thing as JSON. In the end, I want it to look something like this:

{"data":[{"results":"array"}],"overall":{"overall":"map"}}

Here's the code I'm trying to use, but it doesn't work:

def json = new groovy.json.JsonBuilder()
def finalJSON = json {
    data results
    overall overall
}

return json.toString()

But this doesn't work... it throws the following exception:

groovy.lang.MissingPropertyException: No such property: call for class: groovy.sql.GroovyRowResult

I can verify that both variables results and overall have the correct data in them. I guess I'm just not understanding the syntax for JsonBuilder.

soapergem
  • 9,263
  • 18
  • 96
  • 152
  • where is the error thrown? what exactly are results and overall? some SQL results I figure. But what have you done to transform so far etc? – cfrick Dec 09 '14 at 09:04

2 Answers2

1

Find possible solutions below:

import groovy.json.*

def r = [[l:1],[l:2]]
def o = [over:1,all:2]

def json = new JsonBuilder()

json {
    data r
    overall o
}
println json.toPrettyString()

def m = [data: r, overall: o]

println JsonOutput.prettyPrint(JsonOutput.toJson(m))
Opal
  • 81,889
  • 28
  • 189
  • 210
  • 1
    no, there is no root needed. just remove the `all` in your example and it still works and the result is what OP wants. there is something wrong with the data sent into the builder (toString vs actual data) – cfrick Dec 09 '14 at 09:05
  • Thanks @cfrick, it works! Maybe I've failed somewhere. – Opal Dec 09 '14 at 09:06
0

Okay, I figured it out. Groovy's kind of stupid in that you apparently cannot use the same variable name for the value as the key you're assigning. So the real trouble was with the line that read:

overall overall

I changed that variable to overallData and everything started working.

soapergem
  • 9,263
  • 18
  • 96
  • 152