{"record":{"id":"049d8f65388f2703","repo":"JamesNK/Newtonsoft.Json","slug":"cannot-cast-0-to-1","errorCode":null,"errorMessage":"Cannot cast {0} to {1}.","messagePattern":"Cannot cast (.+?) to (.+?)\\.","errorType":"exception","errorClass":"InvalidCastException","httpStatus":null,"severity":"error","filePath":"Src/Newtonsoft.Json/Linq/Extensions.cs","lineNumber":275,"sourceCode":"        {\n            if (token == null)\n            {\n#pragma warning disable CS8653 // A default expression introduces a null value for a type parameter.\n                return default;\n#pragma warning restore CS8653 // A default expression introduces a null value for a type parameter.\n            }\n\n            if (token is U castValue\n                // don't want to cast JValue to its interfaces, want to get the internal value\n                && typeof(U) != typeof(IComparable) && typeof(U) != typeof(IFormattable))\n            {\n                return castValue;\n            }\n            else\n            {\n                if (!(token is JValue value))\n                {\n                    throw new InvalidCastException(\"Cannot cast {0} to {1}.\".FormatWith(CultureInfo.InvariantCulture, token.GetType(), typeof(T)));\n                }\n\n                if (value.Value is U u)\n                {\n                    return u;\n                }\n\n                Type targetType = typeof(U);\n\n                if (ReflectionUtils.IsNullableType(targetType))\n                {\n                    if (value.Value == null)\n                    {\n#pragma warning disable CS8653 // A default expression introduces a null value for a type parameter.\n                        return default;\n#pragma warning restore CS8653 // A default expression introduces a null value for a type parameter.\n                    }\n","sourceCodeStart":257,"sourceCodeEnd":293,"githubUrl":"https://github.com/JamesNK/Newtonsoft.Json/blob/4f73e74372445108d2c1bda37b36e6f5e43402e0/Src/Newtonsoft.Json/Linq/Extensions.cs#L257-L293","documentation":"Thrown by the internal Convert<T,U>(T token) when the token is not directly castable to U and is not a JValue. The conversion path supports (a) tokens that are already assignable to U, and (b) JValue tokens whose underlying .Value is converted via Convert.ChangeType. Any other token type (e.g. JObject, JArray, JProperty when U is a primitive) cannot be converted and raises InvalidCastException naming the token's runtime type and the target type T.","triggerScenarios":"Calling .Value<int>() / .Value<string>() on a JToken that is a JObject/JArray/JProperty (not a JValue); converting a container token to a scalar; mismatched generic type arguments in Value<T,U>.","commonSituations":"Assuming a JToken selected via SelectToken is a scalar when it is actually an object/array; converting LINQ query results whose nodes are containers; off-by-one in a JSONPath selecting a parent instead of a leaf.","solutions":["Navigate to the leaf JValue before converting (e.g. obj[\"foo\"][\"bar\"].Value<int>() selecting a scalar, not obj[\"foo\"]).","Check token.Type == JTokenType.Integer/String/etc. (or token is JValue) before calling Value<T,U>.","Use SelectToken with a more precise JSONPath that resolves to a scalar leaf."],"exampleFix":"// before\nint n = obj.Value<int>(); // obj is JObject, not JValue\n\n// after\nint n = obj[\"count\"].Value<int>();","handlingStrategy":"type-guard","validationCode":"if (token is JValue jv)\n{\n    int n = jv.Value<int>();\n}","typeGuard":"static bool IsLeafValue(JToken t) => t is JValue;\nstatic bool CanConvertTo<T>(JToken t) => t is JValue or T;","tryCatchPattern":null,"preventionTips":["Navigate to the leaf JValue before scalar conversion.","Check token is JValue (or token.Type matches) before Value<T>.","Use precise JSONPath in SelectToken to target scalar leaves."],"tags":["linq-to-json","type-mismatch","casting"],"analyzedSha":"4f73e74372445108d2c1bda37b36e6f5e43402e0","analyzedAt":"2026-08-07T06:10:08.596Z","schemaVersion":2},"datasetVersion":"2026-08-07T07:17:06.508Z"}