2017-06-09 28 views
0

我想使用GET請求的響應json作爲另一個請求的輸入。爲此,我收到的迴應應該是正確的json格式。我正在使用HttpBuilder來做到這一點。如何檢索HTTP獲取響應作爲一個完整的JSON字符串在groovy使用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() 
     } 

當我返回json.toString()它不是一個良好形成的json。我如何做到這一點。當我點擊我的網址時,我看到整個json,但沒有使用上面的代碼。感謝您的幫助。

回答

1

隨着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)) 
    } 
} 

結果:

{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" 
} 
相關問題