{"record":{"id":"76be8e043a51501d","repo":"JamesNK/Newtonsoft.Json","slug":"could-not-convert-0-to-1","errorCode":null,"errorMessage":"Could not convert '{0}' to {1}.","messagePattern":"Could not convert '(.+?)' to (.+?)\\.","errorType":"exception","errorClass":"ArgumentException","httpStatus":null,"severity":"error","filePath":"Src/Newtonsoft.Json/Linq/JToken.cs","lineNumber":2035,"sourceCode":"        public object? ToObject(Type objectType)\n        {\n            if (JsonConvert.DefaultSettings == null)\n            {\n                PrimitiveTypeCode typeCode = ConvertUtils.GetTypeCode(objectType, out bool isEnum);\n\n                if (isEnum)\n                {\n                    if (Type == JTokenType.String)\n                    {\n                        try\n                        {\n                            // use serializer so JsonConverter(typeof(StringEnumConverter)) + EnumMemberAttributes are respected\n                            return ToObject(objectType, JsonSerializer.CreateDefault());\n                        }\n                        catch (Exception ex)\n                        {\n                            Type enumType = objectType.IsEnum() ? objectType : Nullable.GetUnderlyingType(objectType)!;\n                            throw new ArgumentException(\"Could not convert '{0}' to {1}.\".FormatWith(CultureInfo.InvariantCulture, (string?)this, enumType.Name), ex);\n                        }\n                    }\n\n                    if (Type == JTokenType.Integer)\n                    {\n                        Type enumType = objectType.IsEnum() ? objectType : Nullable.GetUnderlyingType(objectType)!;\n                        return Enum.ToObject(enumType, ((JValue)this).Value!);\n                    }\n                }\n\n                switch (typeCode)\n                {\n                    case PrimitiveTypeCode.BooleanNullable:\n                        return (bool?)this;\n                    case PrimitiveTypeCode.Boolean:\n                        return (bool)this;\n                    case PrimitiveTypeCode.CharNullable:\n                        return (char?)this;","sourceCodeStart":2017,"sourceCodeEnd":2053,"githubUrl":"https://github.com/JamesNK/Newtonsoft.Json/blob/4f73e74372445108d2c1bda37b36e6f5e43402e0/Src/Newtonsoft.Json/Linq/JToken.cs#L2017-L2053","documentation":"Thrown inside JToken.ToObject(Type) when the target type is an enum and the token's string value cannot be parsed to that enum. Newtonsoft first tries ToObject via JsonSerializer (to honour StringEnumConverter and [EnumMember] attributes); if that parse throws, the original exception is wrapped and re-thrown as ArgumentException with the offending string value ({0}) and the enum type name ({1}). This is a deliberate re-throw to surface a clearer, value-aware message.","triggerScenarios":"Calling token.ToObject(typeof(MyEnum)) or the generic ToObject<MyEnum>() on a JToken whose JSON value is a string that is not a valid member of the enum, e.g. \"Pendng\" for enum Status { Active, Pending, Closed }. The same path is hit when an integer-as-string or a member renamed via EnumMember is mis-spelled.","commonSituations":"Enum values are renamed in code but the JSON/producer is not updated. A producer sends a free-text status string that does not match any enum member. Locale/casing differences when StringEnumConverter is not configured to be case-insensitive. Migrating from int-backed enums to string-backed enums without regenerating sample data.","solutions":["Inspect the actual string value in the JSON and reconcile it with the enum members (fix the typo or add the missing member).","Configure StringEnumConverter with AllowIntegerValues / camelCase matching, or add [EnumMember(Value = \"...\")] for the producer's spelling.","Parse defensively with Enum.TryParse before calling ToObject, falling back to a default enum value on mismatch."],"exampleFix":"// before\nvar status = token[\"status\"].ToObject<Status>();\n\n// after\nvar raw = (string)token[\"status\"];\nvar status = Enum.TryParse<Status>(raw, ignoreCase: true, out var s) ? s : Status.Unknown;","handlingStrategy":"validation","validationCode":"var raw = (string)token;\nif (!Enum.TryParse<MyEnum>(raw, ignoreCase: true, out _)) { /* handle before ToObject */ }","typeGuard":"static bool IsValidEnumString<TEnum>(string s) where TEnum : struct => Enum.TryParse<TEnum>(s, ignoreCase: true, out _);","tryCatchPattern":"try { return token.ToObject<MyEnum>(); } catch (ArgumentException ex) when (ex.Message.StartsWith(\"Could not convert\")) { /* default or log */ }","preventionTips":["Align producer enum strings with [EnumMember] attributes or a case-insensitive StringEnumConverter.","Validate enum membership with Enum.TryParse before ToObject.","Keep a regression test covering every enum member against sample payloads."],"tags":["enum","deserialization","linq-to-json","string-enum","argumentexception"],"analyzedSha":"4f73e74372445108d2c1bda37b36e6f5e43402e0","analyzedAt":"2026-08-07T06:10:08.596Z","schemaVersion":2},"datasetVersion":"2026-08-07T07:17:06.508Z"}