2017-06-09 2 views
0

abrufen Ich möchte die Antwort JSON einer GET-Anfrage als Eingabe für eine andere Anfrage verwenden. Dafür sollte die Antwort, die ich erhalte, im korrekten json Format sein. Ich verwende HttpBuilder, um dies zu tun.Wie http Get Antwort als eine vollständige JSON String in groovy mit 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() 
     } 

Wenn ich wieder die json.toString() es nicht gut ausgebildet json ist. Wie erreiche ich das? Wenn ich auf meine URL klicke, sehe ich den gesamten JSON, verwende aber den obigen Code nicht. Vielen Dank für Ihre Hilfe.

Antwort

1

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

Ergebnis:

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