Groovy HTTPBuilder 和 Jackson

发布于 2024-12-13 12:39:53 字数 480 浏览 2 评论 0原文

根据请求设置正文时,我可以使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

吾性傲以野 2024-12-20 12:39:53

与其按照接受的答案中的建议手动设置标头并使用错误的 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 )
    }
}

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.

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. The plain text handler gives you an InputReader along with the HttpResponseDecorator. To use Jackson to bind the response to your class, you just need to use an ObjectMapper:

http.request( GET, JSON ) {

    response.success = { resp, reader ->
        def mapper = new ObjectMapper()
        mapper.readValue( reader, Customer.class )
    }
}
十六岁半 2024-12-20 12:39:53

是的。要使用另一个 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!"
    }
}

另请注意,发帖时,您必须设置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:

@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.

天涯离梦残月幽梦 2024-12-20 12:39:53

参加聚会已经很晚了,但现在您可以以更干净的方式执行此操作,特别是在 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)
        }
    }
}

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):

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)
        }
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文