{"record":{"id":"48c23436b59595d1","repo":"JamesNK/Newtonsoft.Json","slug":"can-not-convert-0-to-boolean","errorCode":null,"errorMessage":"Can not convert {0} to Boolean.","messagePattern":"Can not convert (.+?) to Boolean\\.","errorType":"exception","errorClass":"ArgumentException","httpStatus":null,"severity":"error","filePath":"Src/Newtonsoft.Json/Linq/JToken.cs","lineNumber":564,"sourceCode":"        }\n\n        private static bool ValidateToken(JToken o, JTokenType[] validTypes, bool nullable)\n        {\n            return (Array.IndexOf(validTypes, o.Type) != -1) || (nullable && (o.Type == JTokenType.Null || o.Type == JTokenType.Undefined));\n        }\n\n        #region Cast from operators\n        /// <summary>\n        /// Performs an explicit conversion from <see cref=\"Newtonsoft.Json.Linq.JToken\"/> to <see cref=\"System.Boolean\"/>.\n        /// </summary>\n        /// <param name=\"value\">The value.</param>\n        /// <returns>The result of the conversion.</returns>\n        public static explicit operator bool(JToken value)\n        {\n            JValue? v = EnsureValue(value);\n            if (v == null || !ValidateToken(v, BooleanTypes, false))\n            {\n                throw new ArgumentException(\"Can not convert {0} to Boolean.\".FormatWith(CultureInfo.InvariantCulture, GetType(value)));\n            }\n\n#if HAVE_BIG_INTEGER\n            if (v.Value is BigInteger integer)\n            {\n                return Convert.ToBoolean((int)integer);\n            }\n#endif\n\n            return Convert.ToBoolean(v.Value, CultureInfo.InvariantCulture);\n        }\n\n#if HAVE_DATE_TIME_OFFSET\n        /// <summary>\n        /// Performs an explicit conversion from <see cref=\"Newtonsoft.Json.Linq.JToken\"/> to <see cref=\"System.DateTimeOffset\"/>.\n        /// </summary>\n        /// <param name=\"value\">The value.</param>\n        /// <returns>The result of the conversion.</returns>","sourceCodeStart":546,"sourceCodeEnd":582,"githubUrl":"https://github.com/JamesNK/Newtonsoft.Json/blob/4f73e74372445108d2c1bda37b36e6f5e43402e0/Src/Newtonsoft.Json/Linq/JToken.cs#L546-L582","documentation":"Thrown by the explicit (non-nullable) cast operator bool(JToken) at JToken.cs:564. The operator unwraps the token to a JValue and validates its JTokenType against BooleanTypes = {Integer, Float, String, Comment, Raw, Boolean}. If the token is not a JValue at all (e.g. a JObject/JArray) or its type is outside that set (Null, Undefined, Date, Guid, Uri, TimeSpan, Bytes, Object, Array), it raises this ArgumentException.","triggerScenarios":"Casting a JSON null (JTokenType.Null) to (bool)token; casting a JObject/JArray/JConstructor to bool; casting a Date/Guid/Uri/TimeSpan JValue to bool; calling (bool)token where token.Type is Object or Array.","commonSituations":"A JSON schema change that made a previously-boolean field null or an object; consuming an API that omits the field (parsed as null); treating a nested object/array as a scalar boolean.","solutions":["Use the nullable cast (bool?)token and coalesce: ((bool?)token) ?? defaultValue — JSON null then yields null instead of throwing.","Check token.Type == JTokenType.Boolean (or is within Integer/Float/String) before the non-nullable cast.","Use token.Value<bool?>() which tolerates null/missing tokens.","Deserialize into a strongly-typed POCO with a nullable bool property instead of manual casts."],"exampleFix":"// before\nbool active = (bool)token[\"active\"]; // throws when field is null\n\n// after\nbool active = (bool?)token[\"active\"] ?? false;","handlingStrategy":"type-guard","validationCode":"// Verify the token is a boolean-compatible scalar before the non-nullable cast\nstatic bool CanToBool(JToken? t) =>\n    t is JValue v && (v.Type == JTokenType.Boolean || v.Type == JTokenType.Integer\n                      || v.Type == JTokenType.Float || v.Type == JTokenType.String);","typeGuard":"static bool? SafeBool(JToken? t) => t switch {\n    JValue v when v.Type is JTokenType.Boolean or JTokenType.Integer\n                       or JTokenType.Float or JTokenType.String => (bool?)t,\n    JValue v when v.Type is JTokenType.Null or JTokenType.Undefined => null,\n    _ => null\n};","tryCatchPattern":"try\n{\n    bool b = (bool)token;\n}\ncatch (ArgumentException ex) when (ex.Message.StartsWith(\"Can not convert\"))\n{\n    // token type is not boolean-compatible; fall back to default\n}","preventionTips":["Use the nullable cast (bool?)token for optional/nullable boolean fields.","Check token.Type before applying the non-nullable bool cast.","Prefer token.Value<bool?>() which tolerates missing/null tokens.","Deserialize into a nullable bool POCO property for schema-driven safety."],"tags":["linq-to-json","jtoken","cast","boolean","argumentexception"],"analyzedSha":"4f73e74372445108d2c1bda37b36e6f5e43402e0","analyzedAt":"2026-08-07T06:10:08.596Z","schemaVersion":2},"datasetVersion":"2026-08-07T07:17:06.508Z"}