Groovy HTTPBuilder 和 Jackson
根据请求设置正文时,我可以使用 Jackson 而不是 JSON-lib 与 Groovy 的 HTTPBuilder 一起使用吗?
示例:
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
}
}
在此示例中,我在处理响应时使用 Jackson 很好,但我相信请求使用 JSON-lib。
Can I use Jackson instead of JSON-lib with Groovy's HTTPBuilder when setting the body on request?
Example:
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
}
}
In this example, I'm using Jackson fine when handling the response, but I believe the request is using JSON-lib.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
与其按照接受的答案中的建议手动设置标头并使用错误的 ContentType 调用方法,不如覆盖
application/json
的解析器会更干净、更容易。这将导致以与处理纯文本相同的方式处理 JSON 响应。纯文本处理程序为您提供一个
InputReader
以及HttpResponseDecorator
。要使用 Jackson 将响应绑定到您的类,您只需使用ObjectMapper
:Instead of manually setting headers and calling the method with the wrong ContentType as suggested in the accepted answer, It would be cleaner and easier to overwrite the parser for
application/json
.This will cause JSON responses to be handled in the same manner that plain text is handled. The plain text handler gives you an
InputReader
along with theHttpResponseDecorator
. To use Jackson to bind the response to your class, you just need to use anObjectMapper
:是的。要使用另一个 JSON 库来解析响应中传入的 JSON,请将内容类型设置为
ContentType.TEXT
并手动设置 Accept 标头,如下例所示:http://groovy.codehaus.org/modules/http-builder/doc/contentTypes.html。您将收到文本形式的 JSON,然后可以将其传递给 Jackson。要在 POST 请求上设置 JSON 编码输出,只需在使用 Jackson 进行转换后将请求正文设置为字符串即可。示例:
另请注意,发帖时,您必须设置
requestContentType
在设置主体之前。Yes. To use another JSON library to parse incoming JSON on the response, set the content type to
ContentType.TEXT
and set the Accept header manually, as in this example: http://groovy.codehaus.org/modules/http-builder/doc/contentTypes.html. You'll receive the JSON as text, which you can then pass to Jackson.To set JSON encoded output on a POST request, just set request body as a string after you've converted it with Jackson. Example:
Also note that when posting, you have to set the
requestContentType
before setting the body.参加聚会已经很晚了,但现在您可以以更干净的方式执行此操作,特别是在 HTTP 调用过多的地方,例如在测试中(示例是 Spock):
Quite late to the party, but now you can do this in a cleaner way, specially in places with too many HTTP calls, e.g. in tests (example is for Spock):