Is there an easy way to get a JSON dataset from a remote server in Grails?

Is there an easy way to get a JSON dataset from a remote server in Grails?

eg. data at http://example.com/data.json

Data:

 { "firstName": "John", "lastName": "Smith" } 

Groovy code example (theoretical):

 def data = getJson('http://example.com/data.json') println data.firstName // this will print "John" 
+4
source share
2 answers

I believe you should do this:

 import grails.converters.* ... def data = JSON.parse( new URL( 'http://example.com/data.json' ).text ) println data.firstName 
+5
source

You can use the plugin to host Grails , which allows you to execute a REST request in json and allows you to handle all the different types of responses. It is very easy to use.

One example might 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 } } 
+1
source

Source: https://habr.com/ru/post/1334502/


All Articles