2011-11-04 80 views
1

根據請求設置正文時,可以使用Jackson而不是JSON-lib和Groovy的HTTPBuilder嗎?Groovy HTTPBuilder和Jackson

實施例:

client.request(method){ 
     uri.path = path 
     requestContentType = JSON 

     body = customer 

     response.success = { HttpResponseDecorator resp, JSONObject returnedUser -> 

     customer = getMapper().readValue(returnedUser.content[0].toString(), Customer.class) 
     return customer 
     } 
} 

在本例中,我使用的傑克遜精細處理的響應的情況下,但相信該請求正在使用JSON-LIB。

回答

1

是的。要使用其他JSON庫來解析響應中的傳入JSON,請將內容類型設置爲ContentType.TEXT並手動設置Accept報頭,如下例所示:http://groovy.codehaus.org/modules/http-builder/doc/contentTypes.html。您將收到JSON文本,然後您可以將它傳遞給Jackson。

要在POST請求上設置JSON編碼輸出,只需在使用Jackson轉換後將請求主體設置爲字符串即可。例如:

@Grab(group='org.codehaus.groovy.modules.http-builder', module='http-builder', version='0.5.1') 

import groovyx.net.http.* 

new HTTPBuilder('http://localhost:8080/').request(Method.POST) { 
    uri.path = 'myurl' 
    requestContentType = ContentType.JSON 
    body = convertToJSONWithJackson(payload) 

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

另請注意,發佈時,you have to set the requestContentType before setting the body

+0

謝謝。我在迴應中做了類似的事情,但我正在談論編組身體。我會更新這個問題。 –

+0

好的,我已經更新了請求中的JSON答案 – ataylor

6

而不是手動設置標頭,並使用錯誤的ContentType調用方法,如接受的答案中所建議的那樣,將覆蓋application/json的分析器將變得更簡潔和容易。

def http = new HTTPBuilder() 
http.parser.'application/json' = http.parser.'text/plain' 

這將導致JSON響應以與處理純文本相同的方式處理。純文本處理程序會爲您提供InputReader以及HttpResponseDecorator。要使用Jackson將響應綁定到您的課程,您只需使用ObjectMapper

http.request(GET, JSON) { 

    response.success = { resp, reader -> 
     def mapper = new ObjectMapper() 
     mapper.readValue(reader, Customer.class) 
    } 
}