10

I need to retrive a list of tweets, with many informations (easily retrievable from some Tweet.getX() methods) except for the tweet's entire JSON.

I can't figure out how to get the JSON of a tweet belonging from a QueryResult. Anyone can help me?

Raj
  • 22,346
  • 14
  • 99
  • 142
andreaxi
  • 931
  • 5
  • 15
  • 28

2 Answers2

20

You can get the JSON of your tweets by setting setJSONStoreEnabled(true); on the ConfigurationBuilder object that you pass to your TwitterFactory constructor.

Here's a full example:

public static void main(String[] args) throws TwitterException {
    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setJSONStoreEnabled(true);

    Twitter twitter = new TwitterFactory(cb.build()).getInstance();
    Query query = new Query("lizardbill");
    QueryResult result = twitter.search(query);
    for (Tweet tweet : result.getTweets()) {
        System.out.println(tweet.getFromUser() + ":" + tweet.getText());
        String json = DataObjectFactory.getRawJSON(tweet);
        System.out.println(json);
    }
}
Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880
  • Thanks a lot, Bill! Saying "DataObjectFactory.getRawJSON(tweet)" cause another query to Twitter API, right? It's not achievable throught some property of the retrieved tweet, is it? Thank, Andrea – andreaxi Oct 17 '12 at 06:47
  • @andreaxi Unfortunately, no, I don't think the JSON string is saved as a part of the Tweet object. – Bill the Lizard Oct 17 '12 at 10:59
  • Well, I'll find other ways (maybe getting the JSON and then parse it to get the info I need: so just a query for the JSON, and a few of work to parse JSON). Thanks, Bill. – andreaxi Oct 17 '12 at 12:26
  • 6
    `DataObjectFactory` is now deprecated, you need to use `TwitterObjectFactory.jsonStoreEnabled` – Lucas Cimon May 29 '15 at 12:38
  • What if I want to use stream API not search API, how to achieve this? – sareem Jul 19 '17 at 07:33
  • HAA. I knew it. I just wasted my time writing JSON using Jackson JSONGenerator. – Dylan_Larkin Nov 30 '17 at 21:11
0

I think Bill answered the question but those who are still wondering about using TwitterObjectFactory, I believe it's done like this:

ResponseList<Status> userTimeline = // init twitter instance

userTimeline.forEach(x -> {
        String json = TwitterObjectFactory.getRawJSON(x);
        System.out.println(json);
    });