Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

json.NET parsing issue with twitter API data

I have been using json.NET successfully in projects for some time now without any problems. Last night I ran into my first case where json.NET crashed trying to parse json data returned from what should be a reliable source: the twitter API.

Specifically, this code causes the error:

string sCmdStr = String.Format("https://api.twitter.com/1/users/lookup.json?screen_name={0}", sParam);
string strJson = _oauth.APIWebRequest("GET", sCmdStr, null);
JObject jsonDat = JObject.Parse(strJson);

In my case the sParam string contained about 25 twitter numeric Ids. The twitter API call succeeded, but the json.NET Parse call failed with the following error:

"Error reading JObject from JsonReader. Current JsonReader item is not an object: StartArray"

Has anyone else run into this? Does anyone know any way around it? I am at a dead stop until I solve it.

like image 722
Drew Stoddard Avatar asked Nov 11 '11 23:11

Drew Stoddard


1 Answers

I was getting the exact same error and eventually figured it out. Instead of using JObject.Parse use JArray.Parse. So here is your code:

string sCmdStr = String.Format("https://api.twitter.com/1/users/lookup.json?screen_name={0}", sParam);
string strJson = _oauth.APIWebRequest("GET", sCmdStr, null);
JArray jsonDat = JArray.Parse(strJson);

You can then loop through the array and create a jobject for each individual tweet.

for(int x = 0; x < jsonDat.Count(); x++)
{
     JObject tweet = JObject.Parse(jsonDat[x].toString());
     string tweettext = tweet["text"].toString();
     //whatever else you want to look up
}
like image 84
Rochelle C Avatar answered Sep 29 '22 10:09

Rochelle C