Gautam S. Thakur
Gautam S. Thakur

Reputation: 71

Twitter raw JSON Spring social Twitter

How to get original JSON data tweet using spring social Twitter API ? There is "Tweet" class, but I didn't find any function that allows to retrieve original tweet content- returned by Twitter in JSON format.

Upvotes: 1

Views: 342

Answers (1)

Sanjay Rawat
Sanjay Rawat

Reputation: 2374

I don't know why do you want the raw JSON data but it is possible and here is how you can fetch it:

Follow this Guide to setup Spring Social Twitter.

If you want raw JSON data from Twitter then you can use the RestTemplate obtained from TwitterTemplate.

Add this Controller in above guide:

@Controller
@RequestMapping("/jsontweets")
public class JsonTweetsController {

    private ConnectionRepository connectionRepository;

    private TwitterTemplate twitterTemplate;

    @Inject
    public JsonTweetsController(Twitter twitter, ConnectionRepository connectionRepository, TwitterTemplate twitterTemplate) {
        this.connectionRepository = connectionRepository;
        this.twitterTemplate = twitterTemplate;
    }

    @RequestMapping(method=RequestMethod.GET)
    public String helloTwitter(@RequestParam String search, Model model) {
        if (connectionRepository.findPrimaryConnection(Twitter.class) == null) {
            return "redirect:/connect/twitter";
        }

        Connection<Twitter> con = connectionRepository.findPrimaryConnection(Twitter.class);
        UserProfile userProfile = con.fetchUserProfile();
        String username =  userProfile.getFirstName() + " " + userProfile.getLastName(); 

        RestTemplate restTemplate = twitterTemplate.getRestTemplate();

        //More Query Options @ https://dev.twitter.com/rest/reference/get/search/tweets    
        String response = restTemplate.getForObject("https://api.twitter.com/1.1/search/tweets.json?q="+search, String.class);
        System.out.println("JSON Response From Twitter: "+response);

        model.addAttribute("jsonstring", response);
        model.addAttribute("username", username);

        return "json";
    }

}

Add a template to view raw tweets json.html:

<!DOCTYPE html>
<html>
    <head>
        <title>JSON Tweets</title>
    </head>
    <body>
        <h3>Hello, <span th:text="${username}">Some User</span>!</h3>
        <div th:text="${jsonstring}">JSON Tweets</div>
    </body>
</html>

Check the complete Project and the latest Commit for above code.

Upvotes: 1

Related Questions