json.NET parsing issue with twitter API data

2019-04-08 19:42发布

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.

1条回答
兄弟一词,经得起流年.
2楼-- · 2019-04-08 20:01

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
}
查看更多
登录 后发表回答