2

I am doing encryption/decryption of my appsettings.json file within my ASP.NET application.

After decryption, my file is correctly decrypted to the following string:



{
  "ConnectionStrings": {
    "IdentityServer4": "server=(localdb)\\mssqllocaldb;database=IdentityServer4.Quickstart.EntityFramework;trusted_connection=yes"
  }
}

I would now like to convert that result to an object, which I attempt to do using the following line of code:

dynamic result = JsonConvert.DeserializeObject(jsonString);

When that line executes, I receive the following error:

"Unexpected character encountered while parsing value: . Path '', line 0, position 0."
blgrnboy
  • 4,877
  • 10
  • 43
  • 94
  • Have you logged the jsonString variable to verify that it contains valid JSON? – Doug Dawson Jun 07 '17 at 18:53
  • 1
    Possibly there's a [BOM](https://en.wikipedia.org/wiki/Byte_order_mark) at the beginning of the string. If so, see for instance [here](https://stackoverflow.com/q/1317700/3744182) for suggestions on how to resolve. – dbc Jun 07 '17 at 18:53
  • 1
    @dbc, you are absolutely correct. Doing a `jsonString = jsonString.Trim(new char[] { '\uFEFF', '\u200B' });` resolved this. Please submit an answer so I can accept. – blgrnboy Jun 07 '17 at 19:10

1 Answers1

0

It seems there is a Byte Order Mark at the beginning of the string.

To strip the BOM, see answers to this question.

However, it would be better not to include it in the string to begin with. If you have a byte array that includes a BOM and do:

var jsonString = Encoding.UTF8.GetString(byteArray);

Then the BOM will be included. But if you read the binary data with a StreamReader then the BOM will be processed and removed:

var jsonString = new StreamReader(new MemoryStream(byteArray)).ReadToEnd();

(You could add using statements to that if you prefer, although MemoryStream doesn't actually need to be disposed.)

Or, stream, decrypt and deserialize all at once along the lines of this answer (for XML) and this one (for simultaneous decompression and deserialization of JSON).

dbc
  • 104,963
  • 20
  • 228
  • 340