Forum Discussion

tomaszarmata's avatar
tomaszarmata
Contributor
9 years ago
Solved

Building json using JsonOutput

Hello,   I need to produce json looks like:   { "method": "GET", "path": "news", "synchronization-type": 2 } I have tried to do somethink like this:   import groovy.json.JsonOutput...
  • nmrao's avatar
    9 years ago

    Here one way of doing using jackson libraries:

     

    import com.fasterxml.jackson.annotation.JsonProperty
    import com.fasterxml.jackson.databind.ObjectMapper
    import com.fasterxml.jackson.databind.SerializationFeature
    
    class Synchronize {
        String method
        String path
        @JsonProperty("synchronization-type")
        int synchronizationType
    }
    
    def synch = new Synchronize(method:'GET', path:'news', synchronizationType:2)
    ObjectMapper mapper = new ObjectMapper()
    mapper.configure(SerializationFeature.INDENT_OUTPUT,true)
    println(mapper.writeValueAsString(synch))

    Get the depenency libraries from here

     

    OUTPUT

    {
      "method" : "GET",
      "path" : "news",
      "synchronization-type" : 2
    }
  • nmrao's avatar
    9 years ago

    Another simplest way to produce the same output(without having to use java object ) and without additional third party libraries

     

     

    import groovy.json.JsonBuilder
    def json = new JsonBuilder()
    json {
        method 'GET'
        path 'news'
        "synchronization-type" 2
    }
    println json.toPrettyString()

     

    You may also look at the link for array example