2

我的代码如下所示:

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 元素。最重要的问题是“数据”作为地图返回,而不是真正的 Json。没有显示,但我的第一次尝试,我刚刚通过parseText(json.data) 给出了一个关于无法解析 HashMap 的错误。

所以我的问题是:如何让 JsonSlurper 解析从 RESTClient 返回的 JSON?

4

3 回答 3

7

RESTClient类自动解析内容,似乎无法阻止它这样做。

但是,如果您使用HTTPBuilder,您可以重载该行为。您希望将信息作为文本返回,但如果您只设置contentTypeas TEXT,它将不起作用,因为HTTPBuilder使用HTTPBuilder.get()contentType方法的参数来确定要发送的 HTTP Header 以及对返回的对象进行解析。在这种情况下,您需要在标头中,但您想要解析(即不解析)。Acceptapplication/jsonAcceptTEXT

你解决这个问题的方法是在调用它之前Accept在对象上设置标题。这会覆盖原本会在其上设置的标头。下面的代码为我运行。HTTPBuilderget()

@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)
于 2013-07-22T15:06:42.277 回答
2

来自 RESTClient 的响应类型将取决于以下版本:

org.codehaus.groovy.modules.http-builder:http-builder

例如,使用 version 0.5.2,我得到了net.sf.json.JSONObject回报。

在 version0.7.1中,它现在根据问题的观察返回一个 HashMap。

当它是一张地图时,您可以使用普通的地图操作简单地访问 JSON 数据:

def jsonMap = restClientResponse.getData() def user = jsonMap.get("user") ....

于 2015-11-02T19:12:04.060 回答
1

jesseplymale 发布的解决方案也对我有用。

HttpBuilder 对一些 appache 库有依赖关系,因此为了避免将此依赖项添加到您的项目中,您可以在不使用 HttpBuilder 的情况下采用此解决方案:

def jsonSlurperRequest(urlString) {
    def url = new URL(urlString)
    def connection = (HttpURLConnection)url.openConnection()
    connection.setRequestMethod("GET")
    connection.setRequestProperty("Accept", "application/json")
    connection.setRequestProperty("User-Agent", "Mozilla/5.0")
    new JsonSlurper().parse(connection.getInputStream())
}
于 2015-08-25T22:41:26.533 回答