MSL
MSL

Reputation: 1010

Newtonsoft DeserializeObject "True" Case Insensitive

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?

Upvotes: 0

Views: 1652

Answers (2)

Charlieface
Charlieface

Reputation: 72039

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

Upvotes: 0

Evk
Evk

Reputation: 101533

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).

Upvotes: 1

Related Questions