fsi
fsi

Reputation: 1367

Render result as real JSON, not arraylist

I have some trouble in this question, but his problem is quite hard for me to understand the jsonbuilder... Below I have my array rendering as JSON using createCriteria.

render result as JSON
//output
[[1,"a"],[1,"b"],[1,"c"],[1,"d"],[2,"e"]]

How can transform it to json like this?

[{"quantity":1,"week":"a"},{"quantity":1,"week":"b"},{"quantity":2,"week":"c"}]

Upvotes: 0

Views: 216

Answers (2)

Olivier Meurice
Olivier Meurice

Reputation: 562

class JsonTest {    

    public static void main(String [] args) {
        def jsonSlurper = new groovy.json.JsonSlurper()
        def data = [[1,"a"],[1,"b"],[1,"c"],[1,"d"],[2,"e"]]
        List<JsonObject> array = new ArrayList<JsonObject>()
        data.each{quantity,week -> array.add(new JsonObject(quantity, week))}
        println new groovy.json.JsonBuilder(array).toPrettyString()
    }  
}

class JsonObject {

    Integer quantity
    String week

    public JsonObject(Integer quantity, String week) {
        this.quantity = quantity
        this.week = week
    }
}

Upvotes: 0

tim_yates
tim_yates

Reputation: 171194

result.collect { [quantity: it[0], week:it[1]]} as JSON

Upvotes: 2

Related Questions