我有这样的代码:
def client = new groovyx.net.http.RESTClient('myRestFulURL')
def json = client.get(contentType: JSON)
net.sf.json.JSON jsonData = json.data as net.sf.json.JSON
def slurper = new JsonSlurper().parseText(jsonData)
然而,它不起作用! :( 上面的代码在 parseText 中给出了一个错误,因为没有引用 json 元素。最重要的问题是“数据”作为 Map 返回,而不是真正的 Json。没有显示,但我的第一次尝试,我刚刚通过parseText(json.data) 给出了关于无法解析 HashMap 的错误。
所以我的问题是:如何让 JsonSlurper 解析从 RESTClient 返回的 JSON?
最佳答案
RESTClient类会自动解析内容,似乎无法阻止它这样做。
但是,如果您使用 HTTPBuilder你可以重载行为。您希望以文本形式返回信息,但如果您仅将 contentType
设置为 TEXT
,则无法正常工作,因为 HTTPBuilder
使用 HTTPBuilder.get() 的 contentType
参数方法来确定要发送的 Accept
HTTP header ,以及要对返回的对象进行的解析。在这种情况下,您需要在 Accept
header 中使用 application/json
,但您希望对 TEXT
进行解析(即不进行解析)。
解决这个问题的方法是在调用 get()
之前在 HTTPBuilder
对象上设置 Accept
header 。这会覆盖否则会在其上设置的 header 。下面的代码为我运行。
@Grab(group='org.codehaus.groovy.modules.http-builder', module='http-builder', version='0.6')
import static groovyx.net.http.ContentType.TEXT
def client = new groovyx.net.http.HTTPBuilder('myRestFulURL')
client.setHeaders(Accept: 'application/json')
def json = client.get(contentType: TEXT)
def slurper = new groovy.json.JsonSlurper().parse(json)
关于json - 如何从 Groovy 中的 REST 客户端获取 Slurpable 数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17789858/