是否有一种从Grails中的远程服务器获取JSON数据集的简单方法?
e.g。 http://example.com/data.json
数据:
{
"firstName": "John",
"lastName": "Smith"
}
示例Groovy代码(理论):
def data = getJson('http://example.com/data.json')
println data.firstName // this will print "John"
答案 0 :(得分:5)
我相信你应该能够做到:
import grails.converters.*
...
def data = JSON.parse( new URL( 'http://example.com/data.json' ).text )
println data.firstName
答案 1 :(得分:1)
您可以使用允许您在json中执行REST请求的Grails rest plug in,并允许您处理所有不同的响应类型。它非常易于使用。
一个例子是:
import groovyx.net.http.HTTPBuilder
import groovyx.net.http.ResponseParseException
import net.sf.json.JSONException
import static groovyx.net.http.ContentType.JSON
import static groovyx.net.http.Method.GET
...
def restMethod() {
try {
def http = new HTTPBuilder("http://www.example.com")
def path = "/exampleService/info"
http.request(Method.POST, JSON) {req ->
uri.path = path
contentType = 'application/json; charset=UTF-8'
body = "{\"arg1\":\"value4Arg1\"}"
response.success = {resp, json ->
// do something with the json response
}
response.failure = {resp ->
// return some error code
}
}
} catch (JSONException jsonException) {
// do something with the exception
} catch (ResponseParseException parseException) {
// do something with the exception
} catch (Exception e) {
// do something with the exception
}
}