1

要求に応じて本文を設定するときに、Groovy の HTTPBuilder で JSON-lib の代わりに 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
      }
}

この例では、応答を処理するときに Jackson を使用していますが、要求は JSON-lib を使用していると思います。

4

3 に答える 3

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 )
    }
}
于 2012-12-04T03:10:08.167 に答える
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!"
    }
}

また、投稿するときは、 bodyを設定する前に を設定する必要がrequestContentTypeあることに注意してください。

于 2011-11-04T20:44:20.037 に答える