Extending RestFB model with extra fields

RestFB is a simple and flexible Facebook Graph API client for Java. I have used it recently for one of my projects and it greatly simplifies the graph requests. However, as the Graph API is constantly changing, it is really hard for the developers to keep updated with the latest additions in the graph api. I found that the Post model in RestFB representing the news feed posts didn’t have any story field to represent the story being posted on Facebook. RestFB makes it really simple to extend the existing models with extra information without having to change anything in the library code. To add the story field, I created a custom class PostWithStory containing the field. All we need to have the field is to create a new data member and annotate it with @Facebook.

import com.restfb.Facebook;
import com.restfb.types.Post;

public class PostWithStory extends Post {

    @Facebook("story")
    private String story;

    public String getStory() {
        return story;
    }

    public void setStory(String story) {
        this.story = story;
    }
}

Now, when retrieving the posts from news feed, I use the following to get my posts with the story field.

Connection<PostWithStory> myFeed = facebookClient.fetchConnection("me/home", PostWithStory.class);

If you want to have more control on the data that is being returned, you can have a method in the custom class annotated with @JsonMappingCopmleted and it will be called after RestFB finishes mapping the Jsonobject.

// You can annotate methods with @JsonMappingCompleted to perform
// post-mapping operations.
//
// This is useful if you want to massage the data FB returns.

@JsonMappingCompleted
void allDone(JsonMapper jsonMapper) {
  if(lotsOfNumbers.size() == 0)
    throw new IllegalStateException("I was expecting more numbers!");
}
Published 3 Jan 2013

I build mobile and web applications. Full Stack, Rails, React, Typescript, Kotlin, Swift
Pulkit Goyal on Twitter