我从 twitter 检索数据并将其存储在List<>中。当尝试将其存储到 MongoDb 时,我收到错误信息。 " main"中的例外情况线程twitter4j.ResponseListImpl无法强制转换为com.mongodb.BasicDBObject
import java.net.UnknownHostException;
import java.util.List;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.Mongo;
import com.mongodb.MongoException;
import twitter4j.ResponseList;
import twitter4j.Status;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.conf.ConfigurationBuilder;
public class SampleTwitter_data {
public static void main(String[] args) throws TwitterException, UnknownHostException, MongoException {
ConfigurationBuilder cofigurationBuilder =new ConfigurationBuilder();
cofigurationBuilder.setDebugEnabled(true)
.setOAuthConsumerKey("----------")
.setOAuthConsumerSecret("----------")
.setOAuthAccessToken("----------")
.setOAuthAccessTokenSecret("----------");
/**** Connect to MongoDB ****/
Mongo mongo = new Mongo("localhost", 27017);
/**** Get database ****/
// if database doesn't exists, MongoDB will create it for you
DB db = mongo.getDB("mydb");
/**** Get collection / table from 'sample' ****/
// if collection doesn't exists, MongoDB will create it for you
DBCollection table = db.getCollection("sample");
/**** Getting Data From Twitter time line ****/
TwitterFactory tf = new TwitterFactory(cofigurationBuilder.build());
twitter4j.Twitter twitter=tf.getInstance();
ResponseList<Status> status= twitter.getHomeTimeline();
for(Status s:status)
{
/**** here i'm getting error****/
BasicDBObject document = new BasicDBObject();
document=(BasicDBObject) status;
table.insert(document);
/**** just to make sure that i'm retrieving data from Twitter ****/
System.out.println(s.getId()+s.getUser().getName()+" "+s.getText());
}
}
}
答案 0 :(得分:0)
Status
不是Json,你应该先转换它。
在cofigurationBuilder
上,你必须设置JSONStorEnabled为真
cb.setDebugEnabled(true).setOAuthConsumerKey(consumer_key")
.setOAuthConsumerSecret("consumer_key_secret")
.setOAuthAccessToken("access_token")
.setOAuthAccessTokenSecret("access_token_secret")
.setJSONStoreEnabled(true);
并且
BasicDBObject document = new BasicDBObject();
document=(BasicDBObject) status;
您需要从状态创建Json并使用mongo
解析它 String json = TwitterObjectFactory.getRawJSON(status);
DBObject dbObject = (DBObject) JSON.parse(json);
collection.insert(dbObject);