2011-11-04 3 views
1

요청시 본문을 설정할 때 Groovy의 HTTPBuilder에서 JSON-lib 대신 Jackson을 사용할 수 있습니까?Groovy HTTPBuilder 및 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 
     } 
} 

, 나는 잭슨의 벌금을 사용하고 있습니다,하지만 난 요청이 JSON-lib 디렉토리를 사용하고 생각합니다.

답변

1

예. 다른 JSON 라이브러리를 사용하여 응답에서 들어오는 JSON을 구문 분석하려면 콘텐츠 유형을 ContentType.TEXT으로 설정하고이 예의 경우 Accept 헤더를 수동으로 설정하십시오. http://groovy.codehaus.org/modules/http-builder/doc/contentTypes.html. JSON을 텍스트로 받아서 Jackson으로 전달할 수 있습니다.

POST 요청에서 JSON 인코딩 된 출력을 설정하려면 잭슨으로 변환 한 후에 요청 본문을 문자열로 설정하면됩니다. 예 :

@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에 유의하십시오.

+0

감사합니다. 나는 반응과 비슷한 것을하고 있지만, 나는 시체를 마샬링하는 것에 대해 이야기하고있다. 나는 그 질문을 갱신 할 것이다. –

+0

좋아요, 요청시 JSON에 대한 답변도 업데이트했습니다. – ataylor

6

수동으로 헤더를 설정하고 받아 들인 대답에 제안 된대로 잘못된 ContentType으로 메서드를 호출하는 대신 더 깨끗하고 더 쉽게 application/json의 파서를 덮어 쓸 수 있습니다.

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

이렇게하면 JSON 응답이 일반 텍스트가 처리되는 것과 같은 방식으로 처리됩니다. 일반 텍스트 처리기는 HttpResponseDecorator과 함께 InputReader을 제공합니다. Jackson을 사용하여 클래스에 응답을 바인딩하려면 ObjectMapper을 사용해야합니다.

http.request(GET, JSON) { 

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