2011-11-04 79 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) 
    } 
}