jsongroovyjacksonhttpbuilder

Groovy HTTPBuilder and Jackson


Can I use Jackson instead of JSON-lib with Groovy's HTTPBuilder when setting the body on request?

Example:

client.request(method){
      uri.path = path
      requestContentType = JSON

      body = customer

      response.success = { HttpResponseDecorator resp, JSONObject returnedUser ->

        customer = getMapper().readValue(returnedUser.content[0].toString(), Customer.class)
        return customer
      }
}

In this example, I'm using Jackson fine when handling the response, but I believe the request is using JSON-lib.


Solution

  • Yes. To use another JSON library to parse incoming JSON on the response, set the content type to ContentType.TEXT and set the Accept header manually, as in this example: http://groovy.codehaus.org/modules/http-builder/doc/contentTypes.html. You'll receive the JSON as text, which you can then pass to Jackson.

    To set JSON encoded output on a POST request, just set request body as a string after you've converted it with Jackson. Example:

    @Grab(group='org.codehaus.groovy.modules.http-builder', module='http-builder', version='0.5.1' )
    
    import groovyx.net.http.*
    
    new HTTPBuilder('http://localhost:8080/').request(Method.POST) {
        uri.path = 'myurl'
        requestContentType = ContentType.JSON
        body = convertToJSONWithJackson(payload)
    
        response.success = { resp ->
            println "success!"
        }
    }
    

    Also note that when posting, you have to set the requestContentType before setting the body.