0

我有一个服务,我使用以下格式返回数据构建\使用。

def responseData = [
'results': results,
'status': results ? "OK" : "Nothing present"
]

render(responseData as JSON)

输出看起来是这样的,我已经根据 Fiddler 验证了输出

{"results":[{"class":"com.companyName.srm.ods.territory.Apo","id":2,"apoId":"5T9B0"}],"status":"OK"}

这是一个简单的 POST 调用,其中包含来自搜索的参数主体。

使用 HTTPBuilder 我得到了不同的结果

http.request(groovyx.net.http.Method.POST, groovyx.net.http.ContentType.URLENC) {req ->
        uri.path = restUrl
        body = requestData
        response.success = {resp, json ->
            println resp.statusLine.statusCode
            println resp.statusLine
            def slurper = new JsonSlurper()
            String s = json.toString()
            println s
            returnJson = slurper.parseText(s)
        }
        response."422" = {resp, json ->
            println ${resp.statusLine}
        }
        response.failure = {resp ->
            println ${resp.statusLine}
        }
    }

["results":[{"class":"com.companyName.srm.ods.territory.Apo","id":2,"apoId":"5T9B0"}],"status":"OK":null ]

这变成了一个映射对,其中键是 JSON,值是 null,这对于 HTTPBuilder 这样做的原因感到困惑。

为了解析为 JSON,我必须进行以下附加编码 s = s.replace(':null]', '') s = s.replace('[', '')

对于这种类型的实现,这似乎过于复杂。我已经开始调试,没有什么有趣的东西来自于此。有任何想法吗

4

1 回答 1

0

我使用 builder 0.7.1 并通过以下方式获得 json 响应:

http.request(Method.POST, ContentType.TEXT) {
            uri.path = pathToService          
            headers.'User' = user
            headers.Accept = 'application/json'
            body  = requestBody  //here I post some json 

            response.success = { resp, reader ->

                //println reader.text;
                println "response status: ${resp.statusLine}"
                return = reader.text
            }

            response.failure = { resp, reader ->
                println "Request failed with status ${resp.status}"
                reader.responseData.results.each {
                println "  ${it.titleNoFormatting} : ${it.visibleUrl}"
                }
            }
        }
于 2014-04-12T20:20:29.547 回答