Cannot deserialize some tweets using NewtonSoft.Json
-
22-04-2021 - |
Pregunta
Hi All,
I am running a C# console app that is using the Twitter Stream API. My code is below
JToken json = JObject.Parse(ResponseStream.ReadLine());
For every +- 20 tweets, I get the following error "Error reading JObject from JsonReader".
I copied the json into JSONLint and it is valid, so I am perplexed to why this keeps happening. Has anyone else had this error?
Solución 2
I found the issue. Sometimes the stream returns an empty string. Therefore parsing an empty string will throw an error. An example below on how I protected against it:
public static void ProccessTweet(object objMessage)
{
if(objMessage.ToString() != "")
{
var json = JObject.Parse(objMessage.ToString());
if (json["retweeted_status"] == null)
{
var message = ProcessNewTweet(json);
Db.Votes.Add(new FNBVote
{
Message = message,
Entry = Db.Entries.Find(message.Entry.EntryId)
});
return;
}
ProcessRetweet(json);
}
}
Otros consejos
Yes, and it just started happening recently. I believe it is either a bug with NewtonSoft.Json or a change in the twitter api causing it to send bad jsons. I did a packet capture and found the offending character by counting them, but I didn't see anything wrong. I think we will just have to wait for this bug to be fixed.
update I downgraded Newtonsoft.Json.dll to 4.3.* and it works fine.