Search code examples
c#json.net

Getting an error "No token to close. Path ''." from JsonWriter (NewtonSoft.Json 13.0.1)


The following code sample:

using (JsonWriter writer = new JsonTextWriter(sw))
{
    writer.Formatting = Formatting.Indented;
    
    writer.WriteStartObject();

    writer.WritePropertyName("client_id");
    writer.WriteValue(_clientID);
    writer.WritePropertyName("client_secret");
    writer.WriteValue(_clientSecret);
    writer.WritePropertyName("audience");
    writer.WriteValue(_audience);
    writer.WritePropertyName("grant_type");
    writer.WriteValue(_grantType);
    writer.WriteEnd();
    writer.WriteEndObject();
}

Console.WriteLine(sw.ToString());

Fails with the message No token to close. Path ''.

No token to close path

What am I doing wrong? I was not able to find an answer through Google.


Solution

  • TL;DR: The problem is you are attempting to close the object twice:

    writer.WriteEnd();
    writer.WriteEndObject();
    

    Remove one of these lines to fix the problem. You don't need both.


    More detailed explanation:

    Calls to WriteStartObject and WriteStartArray must be balanced with a corresponding call to WriteEndObject and WriteEndArray.

    WriteEnd is a convenience method that closes the last token, whatever type it happens to be. So it functions the same as WriteEndObject and WriteEndArray.

    In your code you call WriteStartObject once at the beginning of the method but then you call both WriteEnd and WriteEndObject to end it. The first of these closes the object you started; the second throws an exception because there's nothing to close-- you already closed it.