简体   繁体   English

Groovy HTTPBuilder 和 Jackson

[英]Groovy HTTPBuilder and Jackson

Can I use Jackson instead of JSON-lib with Groovy's HTTPBuilder when setting the body on request?当根据请求设置主体时,我可以使用 Jackson 而不是 JSON-lib 和 Groovy 的 HTTPBuilder 吗?

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.在这个例子中,我在处理响应时很好地使用了 Jackson,但我相信请求使用的是 JSON-lib。

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 .与其像接受的答案中所建议的那样手动设置标题并使用错误的 ContentType 调用方法,不如覆盖application/json的解析器会更清晰、更容易。

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

This will cause JSON responses to be handled in the same manner that plain text is handled.这将导致以与处理纯文本相同的方式处理 JSON 响应。 The plain text handler gives you an InputReader along with the HttpResponseDecorator .纯文本处理程序为您提供InputReaderHttpResponseDecorator To use Jackson to bind the response to your class, you just need to use an ObjectMapper :要使用 Jackson 将响应绑定到您的类,您只需要使用ObjectMapper

http.request( GET, JSON ) {

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

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 .要使用另一个 JSON 库来解析响应中的传入 JSON,请将内容类型设置为ContentType.TEXT并手动设置 Accept 标头,如下例所示: http : //groovy.codehaus.org/modules/http-builder/doc /contentTypes.html You'll receive the JSON as text, which you can then pass to Jackson.您将收到文本形式的 JSON,然后您可以将其传递给 Jackson。

To set JSON encoded output on a POST request, just set request body as a string after you've converted it with Jackson.要在 POST 请求上设置 JSON 编码的输出,只需在使用 Jackson 转换后将请求正文设置为字符串。 Example:例子:

@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!"
    }
}

Also note that when posting, you have to set the requestContentType before setting the body .另请注意,发布时, 您必须在设置 body 之前设置requestContentType

Quite late to the party, but now you can do this in a cleaner way, specially in places with too many HTTP calls, eg in tests (example is for Spock ):聚会已经很晚了,但现在您可以以更简洁的方式执行此操作,特别是在 HTTP 调用过多的地方,例如在测试中(例如Spock ):

def setup() {
    http = configure {
        request.uri = "http://localhost:8080"
        // Get your mapper from somewhere
        Jackson.mapper(delegate, mapper, [APPLICATION_JSON])
        Jackson.use(delegate, [APPLICATION_JSON])
        response.parser([APPLICATION_JSON]) { config, resp ->
            NativeHandlers.Parsers.json(config, resp)
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM