Get json user from json tweet

╄→гoц情女王★ 提交于 2020-02-01 04:29:25

问题


I have a tweet that I had stored in a file. I want to extract the user as a json object and store it in a different file. The following results in 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

How can I set jsonStoreEnabled to true? Or, is there another way of doing it? I don't have to stick with Twitter4j to create jsonUser. I tried json-simple, but the resulting String is not parsable with Twitter4j.


回答1:


TwitterObjectFactory has a variable called registeredAtleastOnce that if false you will get java.lang.IllegalStateException: Apparently jsonStoreEnabled is not set to true.. You can see this page TwitterObjectFactory So, if you don't want that error you will have to make once call to the Twitter API, for example for the first line of your file

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

In that way you wouldn't get that error




回答2:


It turns out that the org.json package was helpful in this case:

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


来源:https://stackoverflow.com/questions/26984298/get-json-user-from-json-tweet

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!