开发者

Is there a simple way to fetch a JSON dataset from a remote server in Grails?

Is there a simple way to fetch a JSON dataset from a remote server in Grails?

e.g. data at http://example.com/data.json

Data:

{
    "firstName": "John",
    "la开发者_运维问答stName": "Smith"
}

example Groovy code (theoretical):

def data = getJson('http://example.com/data.json')
println data.firstName // this will print "John"


I believe you should be able to do:

import grails.converters.*

...

def data = JSON.parse( new URL( 'http://example.com/data.json' ).text )
println data.firstName


You could use the Grails rest plug in which allow you to execute REST request in json and allows you to handle all the different response types. It is very easy to use.

One example would be something like:

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
        }
      }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜