prayagupadhyay
prayagupadhyay

Reputation: 31252

Rendering Json response in grails view

I am querying twitter api to get the tweets with a hashtag in grails 2.1.1.

My Controller is

import grails.converters.*
import org.codehaus.groovy.grails.web.json.*; // package containing JSONObject, JSONArray,...
import groovyx.net.http.*
import static groovyx.net.http.ContentType.*
import static groovyx.net.http.Method.*

    class NepTweetController {
        def index() {
              //def restEndpointUrl = "http://search.twitter.com/search.json?q=%23nepal";
              def restEndpointUrl = "http://search.twitter.com/search.json?q=%23nepal";
              def http = new HTTPBuilder(restEndpointUrl);

              // perform a GET request, expecting JSON response data
              http.request( GET, JSON ) {
                    //uri.path = '/search.json'
                    //uri.query = [ q: '%23nepal' ]
                                response.success = { resp, json ->
                                             // def tweetsResult = json.results;
                                             // List parsedList = JSON.parse(json) as List;
                                             // JSONObject tweetJson = JSON.parse(json);
                                             //def tweetJson = JSON.parse(json);
                                              def tweets = new JSON(json) as Map;

                                              render(view: "index", model: [message: "Request sent" , tweets: tweets]);
                                 }
              }//end of request
        }//end of method
    }

I successfully get the json response as follows :

  {
      "completed_in": 0.017,
      "max_id": 271907240007581696,
      "max_id_str": "271907240007581696",
      "next_page": "?page=2&max_id=271907240007581696&q=%23nepal%2F",
      "page": 1,
      "query": "%23nepal%2F",
      "refresh_url": "?since_id=271907240007581696&q=%23nepal%2F",
      "results": [
        {
          "created_at": "Fri, 23 Nov 2012 09:25:12 +0000",
          "from_user": "iBshnu",
          "from_user_id": 25051623,
          "from_user_id_str": "25051623",
          "from_user_name": "Bishnu Bhattarai",
          "geo": null,
          "id": 271907240007581696,
          "id_str": "271907240007581696",
          "iso_language_code": "ne",
          "metadata": {
            "result_type": "recent"
          },
          "profile_image_url": "http:\/\/a0.twimg.com\/profile_images\/2622309791\/42z33jnw1kak9ttyqkrf_normal.jpeg",
          "profile_image_url_https": "https:\/\/si0.twimg.com\/profile_images\/2622309791\/42z33jnw1kak9ttyqkrf_normal.jpeg",
          "source": "<a href="http:\/\/twitter.com\/">web<\/a>",
          "text": "RT @dipakbhattarai: \u0930\u093e\u0937\u094d\u091f\u094d\u0930\u092a\u0924\u093f \u0921\u093e. \u0930\u093e\u092e\u092c\u0930\u0923 \u092f\u093e\u0926\u0935\u0926\u094d\u0935\u093e\u0930\u093e \u092e\u0919\u094d\u0938\u093f\u0930 \u0967\u096a \u092d\u093f\u0924\u094d\u0930 \u0926\u0932\u0939\u0930\u0941\u0932\u093e\u0908 \u0930\u093e\u0937\u094d\u091f\u094d\u0930\u093f\u092f \u0938\u0939\u092e\u0924\u093f\u0915\u094b \u0938\u0930\u0915\u093e\u0930 \u092c\u0928\u093e\u0909\u0928 \u0906\u0935\u094d\u0939\u093e\u0928\u0964 #Nepal",
          "to_user": null,
          "to_user_id": 0,
          "to_user_id_str": "0",
          "to_user_name": null
        },
        {
          "created_at": "Fri, 23 Nov 2012 09:24:58 +0000",
          "from_user": "Phanindra07",
          "from_user_id": 63104333,
          "from_user_id_str": "63104333",
          "from_user_name": "Phanindra Dahal",
          "geo": null,
          "id": 271907179404095488,
          "id_str": "271907179404095488",
          "iso_language_code": "en",
          "metadata": {
            "result_type": "recent"
          },
          "profile_image_url": "http:\/\/a0.twimg.com\/profile_images\/2417859753\/febstuo4p4zltimnpky0_normal.jpeg",
          "profile_image_url_https": "https:\/\/si0.twimg.com\/profile_images\/2417859753\/febstuo4p4zltimnpky0_normal.jpeg",
          "source": "<a href="http:\/\/twitter.com\/">web<\/a>",
          "text": "RT @DeepakAdk: Chef's assault on #Nepal #Maoist reflects grassroots anger, excellent piece by my #AFP colleague @FrankieTaggart http:\/\/t.co\/M47qJeoD",
          "to_user": null,
          "to_user_id": 0,
          "to_user_id_str": "0",
          "to_user_name": null
        }
[....more....]

My /views/nepTweet/index.gsp is

<meta name='layout' content='main'/>
<b>${message}</b>

<p>Tweets</p>
<g:each in="${tweets}" var="tweet">
     <p>${tweet.text}</p>
</g:each>

But, I get error parsing json to grails Map.

Error I get is :

Error 500: Internal Server Error
URI
/WhoTweetsNepal/nepTweet
Class
groovy.lang.MissingMethodException
Message
No signature of method: grails.converters.JSON.entrySet() is applicable for argument types: () values: [] Possible solutions: every()

I went through How do I access A JSON Object(String) from GSP page?, but couldn't get help.

Helpppp!!!

Upvotes: 0

Views: 6644

Answers (2)

prayagupadhyay
prayagupadhyay

Reputation: 31252

With to the point suggestions from Ian Roberts, I got the solution with my final Controller to be(realising there is no need to parse it) :

import grails.converters.*
import org.codehaus.groovy.grails.web.json.*; // package containing JSONObject, JSONArray,...
import groovyx.net.http.*
import static groovyx.net.http.ContentType.*
import static groovyx.net.http.Method.*


    class NepTweetController {
        def index() {
              def restEndpointUrl = "http://search.twitter.com/search.json?q=%23nepal";
              def http = new HTTPBuilder(restEndpointUrl);

              // perform a GET request, expecting JSON response data
              http.request( GET, ContentType.JSON ) {
                    //uri.path = '/search.json'
                    //uri.query = [ q: '%23nepal' ]
                                response.success = { resp, json ->
                                             def tweetsResult = json.results;

                                              render(view: "index", model: [message: "Request sent" , tweets: tweetsResult]);
                                 }
              }//end of request
        }//end of method
    }

Upvotes: 1

Ian Roberts
Ian Roberts

Reputation: 122414

You definitely want

def tweetJson = JSON.parse(json);

(which will return a JSONObject, which is a Map) instead of

def tweetJson = new JSON(json) as Map;

but it looks like you have a bit of a name clash in your code - presumably the JSON in

http.request( GET, JSON )

is intended to be the HTTPBuilder content type rather than grails.converters.JSON. If you can clear up this name clash (i.e. remove the import static and say ContentType.JSON) then things may run more smoothly.

Upvotes: 4

Related Questions