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.

import groovyx.net.http.*
@Grab(group='org.codehaus.groovy.modules.http-builder', 
    module='http-builder', version='0.5.2' )

def http = new HTTPBuilder( 'http://twitter.com/statuses/' )

http.get( path: 'user_timeline.json', 
        query: [id:'httpbuilder', count:5] ) { resp, json ->
        
    println resp.status
    
    json.each {  // iterate over JSON 'status' object in the response:
        println it.created_at
        println '  ' + it.text
    }
}

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.