{"record":{"id":"c6616e5b07ad2a5d","repo":"JamesNK/Newtonsoft.Json","slug":"could-not-cast-or-convert-from-0-to-1","errorCode":null,"errorMessage":"Could not cast or convert from {0} to {1}.","messagePattern":"Could not cast or convert from (.+?) to (.+?)\\.","errorType":"validation","errorClass":"ArgumentException","httpStatus":null,"severity":"error","filePath":"Src/Newtonsoft.Json/Utilities/ConvertUtils.cs","lineNumber":654,"sourceCode":"                {\n                    return value;\n                }\n\n                Func<object?, object?>? castConverter = CastConverters.Instance.Get(new StructMultiKey<Type, Type>(valueType, targetType));\n                if (castConverter != null)\n                {\n                    return castConverter(value);\n                }\n            }\n            else\n            {\n                if (ReflectionUtils.IsNullable(targetType))\n                {\n                    return null;\n                }\n            }\n\n            throw new ArgumentException(\"Could not cast or convert from {0} to {1}.\".FormatWith(CultureInfo.InvariantCulture, initialType?.ToString() ?? \"{null}\", targetType));\n        }\n\n        public static bool VersionTryParse(string input, [NotNullWhen(true)]out Version? result)\n        {\n#if HAVE_VERSION_TRY_PARSE\n            return Version.TryParse(input, out result);\n#else\n            // improve failure performance with regex?\n            try\n            {\n                result = new Version(input);\n                return true;\n            }\n            catch\n            {\n                result = null;\n                return false;\n            }","sourceCodeStart":636,"sourceCodeEnd":672,"githubUrl":"https://github.com/JamesNK/Newtonsoft.Json/blob/4f73e74372445108d2c1bda37b36e6f5e43402e0/Src/Newtonsoft.Json/Utilities/ConvertUtils.cs#L636-L672","documentation":"EnsureTypeAssignable (ConvertUtils.cs:629-655) is the final fallback inside ConvertOrCast. After TryConvert fails, it checks direct assignability and any implicit/explicit cast operator (CastConverters). If the value still can't be assigned or cast to the target type, it throws ArgumentException at ConvertUtils.cs:654. The message reports the initial type (or {null}) and the target type.","triggerScenarios":"The deserialization/conversion pipeline lands a value whose runtime type can neither be converted (TryConvert fails) nor cast (not assignable, no cast operator) to the target property type.","commonSituations":"JSON shape doesn't match the .NET model (object where a primitive is expected, or vice versa); missing custom converters; version skew where a member changed type; polymorphic values without TypeNameHandling.","solutions":["Align the .NET model with the actual JSON shape (e.g. model a nested object instead of a primitive).","Register a JsonConverter for the mismatched type.","For dynamic/loosely-typed payloads, deserialize to JToken/JObject and inspect manually.","Add an implicit/explicit conversion operator or TypeConverter between the source and target types.","Enable TypeNameHandling if the payload is polymorphic."],"exampleFix":"// before\npublic class Item { public int Count { get; set; } } // JSON: \"count\": { \"value\": 3 }\n// after\npublic class Item { public Count Count { get; set; } } // model the nested object","handlingStrategy":"try-catch","validationCode":"// Before deserialization, sanity-check that the JSON token kind matches the model field kind.\nvar token = JToken.Parse(json);\nif (token[\"count\"] is JObject) throw new InvalidOperationException(\"'count' is an object, model expects a scalar.\");","typeGuard":"static bool AssignableTo(object value, Type target) => value == null ? ReflectionUtils.IsNullable(target) : target.IsAssignableFrom(value.GetType());","tryCatchPattern":"try { return JsonConvert.DeserializeObject<T>(json, settings); } catch (ArgumentException ex) when (ex.Message.Contains(\"Could not cast or convert\")) { /* deserialize to JToken and map manually */ }","preventionTips":["Keep the .NET model aligned with the JSON shape; model nested objects explicitly.","Register JsonConverters for types that need custom mapping.","For dynamic payloads, deserialize to JObject and inspect before mapping.","Add implicit/explicit conversion operators or TypeConverters for custom types."],"tags":["conversion","serialization","type-mismatch","newtonsoft-json"],"analyzedSha":"4f73e74372445108d2c1bda37b36e6f5e43402e0","analyzedAt":"2026-08-07T06:10:08.596Z","schemaVersion":2},"datasetVersion":"2026-08-07T07:17:06.508Z"}