从json tweet获取json用户

时间:2014-11-18 00:03:53

标签: java twitter4j

我有一条我存储在文件中的推文。我想将用户提取为json对象并将其存储在不同的文件中。以下结果为java.lang.IllegalStateException: Apparently jsonStoreEnabled is not set to true.

String jsonStatus; //Content read from a file
Status status = TwitterObjectFactory.createStatus(jsonStatus); //no problem here
String jsonUser = TwitterObjectFactory.getRawJSON(status.getUser()); //Exception

如何将jsonStoreEnabled设为true?或者,还有另一种方法吗?我不必坚持Twitter4j来创建jsonUser。我尝试了json-simple,但结果字符串无法用Twitter4j解析。

2 个答案:

答案 0 :(得分:4)

TwitterObjectFactory有一个名为registeredAtleastOnce的变量,如果为false,则会得到java.lang.IllegalStateException: Apparently jsonStoreEnabled is not set to true.。你可以看到这个页面 TwitterObjectFactory 因此,如果您不想要这个错误,则必须在调用Twitter API时进行调整,例如对于文件的第一行

ConfigurationBuilder cb = new ConfigurationBuilder();
             cb.setDebugEnabled(true)
             .setOAuthConsumerKey(Ckey)
             .setOAuthConsumerSecret(CkeySecret)
             .setOAuthAccessToken(AToken))
             .setOAuthAccessTokenSecret(AtokenSecret)
             .setJSONStoreEnabled(true);
TwitterFactory tf = new TwitterFactory(cb.build());
Twitter twitter = tf.getInstance();
String jsonStatus; //Content read from a file
Status status = TwitterObjectFactory.createStatus(jsonStatus); //your status
User u2 = t.showUser(status.getUser().getScreenName()); // you use the twitter object once
String jsonUser = TwitterObjectFactory.getRawJSON(status.getUser()); //now you won't get the error
System.out.print(jsonUser); //your happy json

这样你就不会得到那个错误

答案 1 :(得分:0)

事实证明org.json包在这种情况下很有用:

public static String extractUser(String rawJSON) {
    return new org.json.JSONObject(rawJSON).get("user").toString();
}