I am trying to parse a JSON object in C# from Twitter using JObject I cannot seem to figure out where the starting point is for the results that I need. For example:
I need to get the following:
- Avatar URL
- Twitter name
- Message
The JSON string looks like the following:
{“completed_in”:0.01,”max_id”:297026363595042816,”max_id_str”:”297026363595042816″,”page”:1,”query”:”UOL01″,”refresh_url”:”?since_id=297026363595042816&q=O1″,”results”:[{“created_at”:”Thu, 31 Jan 2013 16:59:38 +0000″,”from_user”:”CarrieLouiseH”,”from_user_id”:252240491,”from_user_id_str”:”252240491″,”from_user_name”:”Carrie Haworth”,”geo”:null,”id”:297026363595042816,”id_str”:”297026363595042816″,”iso_language_code”:”nl”,”metadata”:{“result_type”:”recent”},”profile_image_url”:”http://a0.twimg.com/profile_images/1721499350/5680_216695890261_521090261_7945528_588811_n_normal.jpg”,”profile_image_url_https”:”https://si0.twimg.com/profile_images/1721499350/5680_216695890261_521090261_7945528_588811_n_normal.jpg”,”source”:”<a href="http://twitter.com/">web</a>”,”text”:”Test #01″,”to_user”:null,”to_user_id”:0,”to_user_id_str”:”0″,”to_user_name”:null}],”results_per_page”:15,”since_id”:0,”since_id_str”:”0″}
My assumption was that if I started at “results” then I could have access to “from_user” etc.. Here is my code (so far):
void DownloadStringCompleted(object senders, DownloadStringCompletedEventArgs e)
{
try
{
List<TwitterItem> contentList = new List<TwitterItem>();
JObject ja = JObject.Parse(e.Result);
int count = 0;
JToken jUser = ja["results"];
var name2 = (string)jUser["from_user_name"];
}catch(Exception e){
MessageBox.Show("There was an error");
}
}
But this just seems to catch the Exception. Anyone have any ideas to where I am going wrong?
The JSON you have is incorrect – the
"of the element results[0][“source”] should be escaped:Also,
ja["results"]is an array. You cannot use the string indexer to get its element. You first need to get the element on the desired index, then you can access itsfrom_user_nameproperty: