Search code examples
c#-4.0twitterconsole-applicationjson.netjsonlint

Cannot deserialize some tweets using NewtonSoft.Json


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?


Solution

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