Thursday, January 15, 2009

Using serialized objects

Here we use the 'update' method from my previous example to create a Status object and get the screen name of the user that posted the status. We can use the screen name to call the 'show' method.

// Make your API calls with this.
private Twitter twitter;

// The responses from the Twitter REST API go here.
private XmlDocument xmlresponse;

// NEVER hard code your password. 
// I'm just trying to keep it simple for the example.
twitter = new Twitter("onil", "{my password}");

// Make a call to the 'update' method to post your status.
xmlresponse = twitter.StatusUpdate("Pooping.");

// Create a Status object using the XML response.
Status myStatus = new Status();
myStatus = (Status)XmlSerializerHelper.Deserialize(xmlresponse, typeof(Status));

// We can use the Status object to pass a parameter to the 'show' method.
// Every status object contains a User object representing the user that
// posted the status. We'll use the User object to get the screen name.
xmlresponse = twitter.UserShow(myStatus.User.Screen_Name);
// We could also have passed myStatus.User.Id in the above example.
// The Twitter REST API will accept the screen name or user ID. It's up to you.

// Create a User object using the XML response.
User myUser = new User();
myUser = (User)XmlSerializerHelper.Deserialize(xmlresponse, typeof(User));

I think that calling the Deserialize method is a bit annoying. TwitterXML will be changed in a future release so that all methods return a the deserialized XML  object instead of an XML document.

No comments:

Post a Comment