json.NET parsing issue with twitter API data

与世无争的帅哥 提交于 2019-12-06 02:45:44

问题


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:


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
}


来源:https://stackoverflow.com/questions/8101049/json-net-parsing-issue-with-twitter-api-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!