4

I want to use the response json of a GET request as an input to another request. For that the response that I receive should be in correct json format. I am using HttpBuilder to do this.

    HTTPBuilder http = new HTTPBuilder(urlParam, ContentType.JSON);
    http.headers.Accept = ContentType.JSON;
    http.parser[ContentType.JSON] = http.parser.'application/json'

    return http.request(GET) {              
        response.success = {resp, json ->
            return json.toString()
        }

When I return the json.toString() it is not a well formed json. How do I achieve that. When I click my get url i see entire json but not using the above code.Thanks for your help.

user2239090
  • 61
  • 2
  • 4

1 Answers1

2

With groovy.json.JsonOutput:

HTTPBuilder http = new HTTPBuilder('http://date.jsontest.com/', ContentType.JSON);
http.headers.Accept = ContentType.JSON
http.parser[ContentType.JSON] = http.parser.'application/json'
http.request(Method.GET) {
    response.success = { resp, json ->
        println json.toString()         // Not valid JSON
        println JsonOutput.toJson(json) // Valid JSON
        println JsonOutput.prettyPrint(JsonOutput.toJson(json))
    }
}

Result:

{time=09:41:21 PM, milliseconds_since_epoch=1497303681991, date=06-12-2017}
{"time":"09:41:21 PM","milliseconds_since_epoch":1497303681991,"date":"06-12-2017"}
{
    "time": "09:41:21 PM",
    "milliseconds_since_epoch": 1497303681991,
    "date": "06-12-2017"
}
Hugues M.
  • 19,846
  • 6
  • 37
  • 65