Sunday, October 25, 2009

Use GSON to access json response in grails action

Communicate with external service through gson
1. download gson package and extract the jar into lib directory
http://code.google.com/p/google-gson/
2. grails action

def fetch={
def data
def reader
try {
URL url = new URL("http://localhost:8080/controller/action");
reader = new BufferedReader(new InputStreamReader(url.openStream()));
JsonParser jp = new JsonParser()
JsonElement je = jp.parse(reader)
data = je.getAt("data");
reader.close()

} catch (MalformedURLException e) {
// ...
} catch (IOException e) {
// ...
} finally {
reader.close()
}
render data;
}

No comments:

Post a Comment