Parsing JSON data

JSON responses can be automatically handled by HTTPBuilder's default content parser registry. It uses JSON-Lib internally to parse the response data into a GPathResult, in a similar manner used by Groovy's XMLSlurper.

The following is a working example (try it!) of accessing a Twitter feed using HTTPBuilder and JSON.

@Grab(group='org.codehaus.groovy.modules.http-builder', module='http-builder', version='0.7' )

import groovyx.net.http.HTTPBuilder

def http = new HTTPBuilder( 'http://api.openweathermap.org/data/2.5/' )

http.get( path: 'weather', query: [q: 'London'] ) { resp, json ->

    println resp.status

    println "It is currently ${json.weather.main[0]} in London."
    println "The temperature is ${json.main.temp} degrees Kelvin"
}

POSTing JSON data

JSON can just as easily be sent in the body of a POST or PUT request. The JSON request encoder can convert a Map, List, POJO, or a closure.

The simplest method is to use a map or list like so:

http.request( POST, JSON ) { req ->
    body = [name:'bob', title:'construction worker']

     response.success = { resp, json ->
        // response handling here
    }
}

Thanks to Json-Lib's JsonGroovyBuilder class, we an also build the request data on-the-fly like so:

  http.request( POST, JSON ) { req ->
      body = [
        first : 'Bob',
        last : 'Builder',
        address : [
          street : '123 Some St',
          town : 'Boston',
          state : 'MA',
          zip : 12345
        ]
      ]

      response.success = { resp, json ->
          // response handling here
      }
  }

See the API documentation for more details.