Search code examples
jsongroovyhttpbuilder

Groovy HttpBuilder json input trouble


I am having issues passing json parameters to a web action. I know that the web action works at the specified url http://projects.example.net/example/bugnetwebservice.asmx/MobileBuildAction, as I have tested it with postman with the json parameters:

{
    featureIdStr: 31,
    actionStr: 1,
    comment: "Hello world"
}

and get the response:

{
    "d": "Succeeded"
}

Whenever I try to run it in groovy, however, I get this response:

Jun 10, 2016 9:54:25 AM net.sf.json.JSONObject _fromBean
INFO: Property 'value' of class org.codehaus.groovy.runtime.GStringImpl has no read method. SKIPPED
Failure: 500

Here is my code:

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

def http = new HTTPBuilder("http://projects.example.net/")
def issueId = 31
def msg = "Build Failed"
def jsonBody = [:]
jsonBody.put("featureIdStr", issueId)
jsonBody.put("actionStr", 0)
jsonBody.put("comment", "${msg}: <a href='http://www.google.com'}'>Googles Job</a>")
http.request(POST, JSON) {
    uri.path = "/example/bugnetwebservice.asmx/MobileBuildAction"
    body = jsonBody

    response.success = { resp ->
        println "Success! ${resp.status}"
    }

    response.failure = { resp ->
        println "Failure: ${resp.status}"
    }
}

Please help!


Solution

  • jsonBody.put("comment", "${msg}: http://www.google.com'}'>Googles Job")

    The "" in Groovy creates a Groovy String (aka the GString). GStrings are great - they allow that ${} syntax - but they have some problems around serializing and deserializing themselves. There's an awesome StackOverflow answer explaining what's up with that.

    Anyway, the short of it is, between that post and my own experience: anytime you're comparing or might be serializing your Groovy String, call toString() on it first.

    I would consider writing your code like:

    def commentValue = "${msg}: <a href='http://www.google.com'}'>Googles Job</a>"
    
    jsonBody.put( commentValue.toString() )