如何使用 Twitter API json 和 java

How to use Twitter API json with java

我正在尝试在 Twitter 上抓取带有特殊#hashtag 的推文,并且从返回的 json 我只需要在 cvs 中导出的推文的 ID、日期、用户 ID 和文本。

我的代码如下所示。

import oauth.signpost.OAuthConsumer;
import oauth.signpost.commonshttp.CommonsHttpOAuthConsumer;

import org.apache.commons.io.IOUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import org.json.*;

public class CrawlTweets {


    static String AccessToken = "xxx";
    static String AccessSecret = "xxx";
    static String ConsumerKey = "xxx";
    static String ConsumerSecret = "xxx";

    /**
     * @param args
     */
    public static void main(String[] args) throws Exception {
        OAuthConsumer consumer = new CommonsHttpOAuthConsumer(
                ConsumerKey,
                ConsumerSecret);

        consumer.setTokenWithSecret(AccessToken, AccessSecret);

HttpGet request = new     HttpGet("https://api.twitter.com/1.1/search/tweets.json?q=%23Nutella&lang=en");
        consumer.sign(request);

        HttpClient client = new DefaultHttpClient();
        HttpResponse response = client.execute(request);


        JSONObject obj = new JSONObject(response);

        String id = obj.get("id").toString();

        System.out.println(id);

    }
}

我得到以下异常:

Exception in thread "main" org.json.JSONException: JSONObject["id"] not     found.
    at org.json.JSONObject.get(JSONObject.java:459)
    at CrawlTweets.main(CrawlTweets.java:41)

代码有什么问题?我怎样才能提取提到的信息并放入 cvs?谢谢。

您(可能)从 Twitter 返回一个错误 - 确保它 responds OK 并且它发送给您的 json 实际上是正确的。

JSON 响应格式并不像您的 obj.get("id") 暗示的那样扁平。

查看示例响应格式 https://dev.twitter.com/rest/reference/get/search/tweets

obj.get("statuses") 会 return 你一个 JSON 数组。您需要以某种方式遍历数组。对于 JSON 数组中的每个元素,将能够拉出一个 elementInArray.getString("id_str").

import org.json.*;

...

JSONArray arr = obj.getJSONArray("statuses");

for (int i = 0; i < arr.length(); i++)
{
    String id = arr.getJSONObject(i).getString("id_str");
    ......
}

用户 Json 如果您得到正确的响应,像 Jackson 这样的图书馆会解析响应!