2017-06-09 4 views
0

Je souhaite utiliser la réponse json d'une requête GET comme entrée pour une autre requête. Pour cela, la réponse que je reçois doit être au format json correct. J'utilise HttpBuilder pour le faire.Comment récupérer la réponse http get en tant que chaîne json complète dans groovy en utilisant httpbuilder

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() 
     } 

Lorsque je retourne le json.toString() ce n'est pas un json bien formé. Comment puis-je y parvenir? Quand je clique sur mon URL, je vois tout le json mais je n'utilise pas le code ci-dessus. Merci pour votre aide.

Répondre

1

Avec 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)) 
    } 
} 

Résultat:

{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" 
}