Search code examples
jsongroovyratpack

Parse json in Ratpack Groovy


I started a small ratpack app in the Groovy console but I couldn't work out from the documentation how to get a hold of json data that has been sent in the request.

@Grab("io.ratpack:ratpack-groovy:0.9.4")
import static ratpack.groovy.Groovy.*
import groovy.json.JsonSlurper

ratpack {
  handlers {
    get {
      def slurper = new JsonSlurper()
      def result = slurper.parseText('{"person":{"name":"Guillaume","age":33,"pets":["dog","cat"]}}')
      render "Hello world! ${result.person}"
    }
    post("foo") {
      def slurper = new JsonSlurper()
      def result = slurper.parseText("WHAT DO i PUT HERE?")
      render "Hello world! ${result.person}"
    }
  }
}

And an example request:

curl -XPOST -H "Content-Type: application/json" -d '{"person":{"name":"Guillaume","age":33,"pets":["dog","cat"]}}' localhost:5050/foo

Solution

  • Ratpack provides a concept known as a Parser that allows you to parse incoming request body to a given type.

    In your case, you could parse incoming request body to a JsonNode, or your own type using the ratpack-jackson module. You can find more information here.

    Here is your example using the parser provided by the ratpack-jackson module:

    @Grab("io.ratpack:ratpack-groovy:0.9.12")     
    @Grab("io.ratpack:ratpack-jackson:0.9.12")    
    
    import static ratpack.groovy.Groovy.*         
    import ratpack.jackson.JacksonModule          
    import static ratpack.jackson.Jackson.jsonNode
    
    ratpack {                                     
      bindings {                                  
        add new JacksonModule()                   
      }                                           
      handlers {                                  
        post("foo") {                             
          def postBody = parse jsonNode()
          render "Hello world! ${postBody.person}"
        }                                         
      }                                           
    }                 
    

    Your curl

    curl -XPOST -H "Content-Type: application/json" -d '{"person":{"name":"Guillaume","age":33,"pets":["dog","cat"]}}' localhost:5050/foo
    

    Responds as

    Hello world! {"name":"Guillaume","age":33,"pets":["dog","cat"]}
    

    I hope this helps!