0

I expected this code to throw an Exception because I am trying to deserialize a string value into a boolean property. However, I was surprised to find that Json.NET happily converts the string value to a boolean. Why? Is there any way to change this behavior, for example a "strict" mode?

using Newtonsoft.Json;

var activeAccount = JsonConvert.DeserializeObject<Account>("{\"active\": \"True\"}");
var inactiveAccount = JsonConvert.DeserializeObject<Account>("{\"active\": \"false\"}");

Console.WriteLine(activeAccount.Active); // True
Console.WriteLine(inactiveAccount.Active); // False

public class Account
{
    public bool Active { get; set; }
}
3
  • Why? Because James Newton-King, the author of Json.NET, wanted to support string values for Booleans. As such this isn't really answerable here. Commented Mar 14 at 19:37
  • 1
    Is there any way to change this behavior, for example a "strict" mode? -- not via settings, see Support "strict mode" for RFC7159 parsing #646. Do you need a workaround? Commented Mar 14 at 19:39
  • No, at this point I just want to know if there is some setting I have overlooked. If Json.NET does not support this behavior then that answers my question. Commented Mar 14 at 19:51

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.