skip to Main Content

I’m trying to deserialize a JSON object. The value of the string ‘plaintext’ is:

{"expiryDay":1,"expiryMonth":6,"expiryYear":2023,"machineGuid":"a3586fb9-b05e-46f1-a4a0-683a97109e34","name":"Alexander Farley"}

This line throws an exception:

var json = JObject.Parse(plaintext);

The exception is:

Newtonsoft.Json.JsonReaderException: 'Additional text encountered after finished reading JSON content: . Path '', line 1, position 129.'

This is surprising to me, because I believe the input is valid JSON. This web utility indicates that the ‘plaintext’ string is valid JSON https://jsonformatter.curiousconcept.com/#

There are many other questions on StackOverflow and elsewhere asking about the same exception, but in those cases, the issue is that they aren’t inputting valid JSON because they have multiple root elements. In my case, I don’t have multiple root elements, so I expect to be able to parse this object without any additional input (i.e. providing a schema object).

Is there something I’m missing? It seems to me that the Newtonsoft library is refusing valid JSON.

2

Answers


  1. Chosen as BEST ANSWER

    As suggested by commenters, the reason for this was extra non-printable bytes following the JSON in the string. This happened because I got the JSON string by decrypting some encrypted text.

    C#'s basic .Trim() and .Trim('') didn't work because there was more than one byte in the string with other garbage in between.

    I used this line to split on the null-char:

    s = s.Split(new[] { '' }, 2)[0];
    

    As copied from an answer here: Help with terminated strings in C#

    The suggestion from user123456 may have worked (I didn't try) but I was mainly interested in finding out why my original approach didn't work rather than getting a workaround.


  2. Create a class and deserilize it

        var outObject = JsonConvert.DeserializeObject<yourclass>(response);
        return outObject;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search