json.NET使用twitter API数据解析问题

时间:2011-11-11 23:07:18

标签: c# twitter json.net

我一直在项目中成功使用json.NET一段时间没有任何问题。昨晚我遇到了第一个案例,其中json.NET崩溃试图解析从应该是可靠来源返回的json数据:twitter API。

具体来说,此代码会导致错误:

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);

在我的情况下,sParam字符串包含大约25个twitter数字ID。 twitter API调用成功,但json.NET Parse调用失败,出现以下错误:

  

“从JsonReader读取JObject时出错。当前JsonReader项不是对象:StartArray”

有没有其他人遇到这个?有谁知道它周围的任何方式?在我解决之前,我处于停滞状态。

1 个答案:

答案 0 :(得分:8)

我得到了完全相同的错误并最终弄明白了。而不是使用JObject.Parse使用JArray.Parse。所以这是你的代码:

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);

然后,您可以遍历数组并为每个推文创建一个jobject。

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
}