Home > Enterprise >  Newtonsoft DeserializeObject "True" Case Insensitive
Newtonsoft DeserializeObject "True" Case Insensitive

Time:11-10

I want to deserialize a simple string "True" to boolean true using Newtonsoft.Json.JsonConvert.DeserializeObject method like this:

var b = Newtonsoft.Json.JsonConvert.DeserializeObject("True");

but it gives me an error. 'Unexpected character encountered while parsing value: T. Path '', line 0, position 0.'

I heard Newtonsoft uses case insensitive deserialization by default

why is this error?

CodePudding user response:

Valid JSON values are:

  • object ({ ... })
  • array ([...])
  • number (1)
  • string ("String")
  • boolean (either true or false, NOT True or False)
  • null (null)

For that reason, "true" is a valid JSON representing single boolean value.

However, "True" is not valid json, it does not represent any of the above values according to specification (it does not represent string, because in this case it should have been ""True"" (with quotes).

CodePudding user response:

As mentioned, a bare True value is simply not valid JSON. So there is no reason for JSON.Net to accept it.

However, it will accept a string value "True" or "true" in place of a bool

var b = Newtonsoft.Json.JsonConvert.DeserializeObject(@"""True""");

// returns true

var f = Newtonsoft.Json.JsonConvert.DeserializeObject(@"""False""");

// returns false

dotnetfiddle

  • Related