Have you ever worked with Twitter and twittter4j and wondered how to parse a Status object to a String in JSON format and the other way around??

Here is the solution!!

To convert it to the JSON string you just need to do this:

Status tweet;
String tweetJson = StriTwitterObjectFactory.getRawJSON(tweet);

And from the JSON string to Status:

String json; //a valid json string
Status status = null;
try {
    status = TwitterObjectFactory.createStatus(json);
} catch (TwitterException e) {
    e.printStackTrace();
}

The exceptions it throws is in the case that the string you provide is not a JSON valid String.

Simple as that!

Advertisements