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
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:
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.
Create a class and deserilize it