Search code examples
jsongroovyjsonbuilder

jsonbuilder: how to create map of objects


I've been trying to create a map of objects with jsonBuilder for a few hours already with no success. What I want to do is to create such json, so that I can adress my objects like this: someJsonObject.elements.2. Desired JSON looks like this (it's perfectly correct syntax):

{
    "elements": {
        "1": {
            "id": 1,
            "x": 111
        },
        "2": {
            "id": 2,
            "x": 222
        },
        "3": {
            "id": 3,
            "x": 333
        }
    }
}

Best results so far I got with this code:

builder.elements() {
    elementList.each { Element e ->
        element( id : e.id, x : e.x )
        println "dodano"
    }
}

But all I get is only one element printed in my json:

{
    "elements": {
        "element": {
            "id": 3,
            "x": 333
        }
    }
}

If I only could name my objects dynamicly, for instance like this:

builder.elements() {
        elementList.each { Element e ->
            e.id( id : e.id, x : e.x )
            println "dodano"
        }
    }

but it gives me an error: No signature of method: com.webwaver.website.Element.id() is applicable for argument types: (java.util.LinkedHashMap) values: [[id:3, x:748]]

Has anyone got any idea how to get desired json?

EDIT: Thank's for answer. That helps a lot, but since I can't use method call builder.elements() I still have got a problem with creating json, that would look like this:

{
    "data": {
        "lastPageNr": 1,
        "lastLanguageId": 1,
        "lastElementNr": 0,
        "websiteId": "nrpntf"
    },
    "elements": {
        "1": {
            "id": 1,
            "x": 111
        },
        "2": {
            "id": 2,
            "x": 222
        },
        "3": {
            "id": 3,
            "x": 333
        }
    }
}

any ideas?


Solution

  • This gives you the output you want:

    import groovy.json.*
    
    def builder = new JsonBuilder()
    builder.elements {
      "1" {
        id 1
        x  111
      }
      "2" {
        id 2
        x  222
      }
      "3" {
        id 2
        x  222
      }
    }
    println builder.toPrettyString()
    

    So what you want for your list based builder is something like:

    def elementList = [ [ id: 3, x:748 ], [ id: 4, x:222 ] ]
    def builder = new JsonBuilder()
    builder.elements {
      elementList.each { e ->
        "$e.id" {
          id e.id
          x  e.x
        }
      }
    }
    println builder.toPrettyString()
    

    Edit -- after you changed the question:

    def builder = new JsonBuilder()
    builder {
      data {
        lastPageNr 1
        lastLanguageId 1
        lastElementNr 0
        websiteId 'nrpntf'
      }
      elements {
        elementList.each { e ->
          "$e.id" {
            id e.id
            x  e.x
          }
        }
      }
    }
    println builder.toPrettyString()