1

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.

afarley
  • 781
  • 6
  • 26
  • 1
    I'm not able to replicate the error. Can you provide a runnable [mcve]? Or even a link to a [dotnetfiddle](https://dotnetfiddle.net/) which demonstrates the problem? It's possible your source string has some whitespace or non-printable character(s) at the end which aren't present here? – David May 19 '23 at 18:38
  • Could you have some [nonprinting characters](https://stackoverflow.com/q/3253247) at the end of your plaintext string? – dbc May 19 '23 at 18:48
  • The string contains many null bytes after the printable text. I'll try trimming it. – afarley May 19 '23 at 18:48
  • If that's the problem, either trim them or see [Discarding garbage characters after json object with Json.Net](https://stackoverflow.com/q/37172263/3744182). – dbc May 19 '23 at 18:56

2 Answers2

0

Create a class and deserilize it

    var outObject = JsonConvert.DeserializeObject<yourclass>(response);
    return outObject;
user123456
  • 2,524
  • 7
  • 30
  • 57
0

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('\0') didn't work because there was more than one \0 byte in the string with other garbage in between.

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

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

As copied from an answer here: Help with \0 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.

afarley
  • 781
  • 6
  • 26