2011-01-06 14 views
4

GrailsのリモートサーバーからJSONデータセットを取得する簡単な方法はありますか?GrailsのリモートサーバからJSONデータセットを取得する簡単な方法はありますか?

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

例のGroovyコード(理論):http://example.com/data.json

データのデータ

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

それはJSONPをサポートしています:

一つの例は、のようなものでしょうか?クロスドメインのAJAXリクエストは、ほとんどの環境で禁止されています(セキュリティ上の理由から、XSSはウェブの最大の問題です)。 – jwueller

+1

@elusiveこれはサーバーサイドなので、JSONP/XSSが適切かどうか分かりません – Armand

答えて

5

私はあなたが行うことができるはずと信じて:

import grails.converters.* 

... 

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

ありがとうございましたtim - 本当に単純ではありませんでした。 – Armand

1

あなたが使用することができますGrails rest plug inでは、jsonでRESTリクエストを実行できるようになり、すべての異なる応答タイプ。それは非常に使いやすいです。

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

こんにちは@Maricel、grails-REST-pluginの使用例を追加できますか? – Armand

+0

@Alison例を追加する答えを編集しました。 – Maricel

+0

私はこれを使用してSSLSocketFactory.java:543でInternal_errorを取得しようとしています。また、変数contentTypeとbodyを使用していますか? –

関連する問題