【问题标题】:Groovy HTTPBuilder and JacksonGroovy HTTPBuilder 和 Jackson
【发布时间】:2011-11-04 20:32:10
【问题描述】:

在根据请求设置正文时,我能否在 Groovy 的 HTTPBuilder 中使用 Jackson 而不是 JSON-lib?

例子:

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。

【问题讨论】:

    标签: json groovy jackson httpbuilder


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

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

      【讨论】:

      • 谢谢。我对响应做了类似的事情,但我说的是编组身体。我会更新问题。
      【解决方案3】:

      聚会晚了,但现在您可以以更简洁的方式执行此操作,特别是在 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)
              }
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-10-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多