{"record":{"id":"354e484927e3cf72","repo":"JamesNK/Newtonsoft.Json","slug":"can-not-convert-null-0-into-non-nullable-1","errorCode":null,"errorMessage":"Can not convert null {0} into non-nullable {1}.","messagePattern":"Can not convert null (.+?) into non-nullable (.+?)\\.","errorType":"exception","errorClass":"Exception","httpStatus":null,"severity":"error","filePath":"Src/Newtonsoft.Json/Utilities/ConvertUtils.cs","lineNumber":389,"sourceCode":"#region TryConvert\n        internal enum ConvertResult\n        {\n            Success = 0,\n            CannotConvertNull = 1,\n            NotInstantiableType = 2,\n            NoValidConversion = 3\n        }\n\n        [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]\n        [RequiresDynamicCode(MiscellaneousUtils.AotWarning)]\n        public static object Convert(object initialValue, CultureInfo culture, Type targetType)\n        {\n            switch (TryConvertInternal(initialValue, culture, targetType, out object? value))\n            {\n                case ConvertResult.Success:\n                    return value!;\n                case ConvertResult.CannotConvertNull:\n                    throw new Exception(\"Can not convert null {0} into non-nullable {1}.\".FormatWith(CultureInfo.InvariantCulture, initialValue.GetType(), targetType));\n                case ConvertResult.NotInstantiableType:\n                    throw new ArgumentException(\"Target type {0} is not a value type or a non-abstract class.\".FormatWith(CultureInfo.InvariantCulture, targetType), nameof(targetType));\n                case ConvertResult.NoValidConversion:\n                    throw new InvalidOperationException(\"Can not convert from {0} to {1}.\".FormatWith(CultureInfo.InvariantCulture, initialValue.GetType(), targetType));\n                default:\n                    throw new InvalidOperationException(\"Unexpected conversion result.\");\n            }\n        }\n\n        [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]\n        [RequiresDynamicCode(MiscellaneousUtils.AotWarning)]\n        private static bool TryConvert(object? initialValue, CultureInfo culture, Type targetType, out object? value)\n        {\n            try\n            {\n                if (TryConvertInternal(initialValue, culture, targetType, out value) == ConvertResult.Success)\n                {\n                    return true;","sourceCodeStart":371,"sourceCodeEnd":407,"githubUrl":"https://github.com/JamesNK/Newtonsoft.Json/blob/4f73e74372445108d2c1bda37b36e6f5e43402e0/Src/Newtonsoft.Json/Utilities/ConvertUtils.cs#L371-L407","documentation":"ConvertUtils.Convert throws this when TryConvertInternal returns ConvertResult.CannotConvertNull (ConvertUtils.cs:388-389). That result is produced when the initial value is DBNull.Value and the target type is a non-nullable value type (ConvertUtils.cs:565-578): DBNull cannot become an int/DateTime/struct. The message reports the initial type and the non-nullable target.","triggerScenarios":"Converting a value that is DBNull.Value into a non-nullable value type via ConvertUtils.Convert — typical when reading from ADO.NET (DataRow/DataReader) where missing DB cells are DBNull.","commonSituations":"Database rows with NULL columns mapped to non-nullable struct properties; DBNull leaking through into a Newtonsoft conversion path (HAVE_ADO_NET builds); integration code passing raw DBNull.","solutions":["Make the target type nullable (int? / Nullable<T>) or a reference type.","Replace DBNull.Value with null (or a sensible default) before invoking Convert.","Filter DBNull at the data-access layer: row.Field<int?>(\"Col\") ?? default.","Use a custom JsonConverter that maps DBNull to default(T)."],"exampleFix":"// before\nint age = (int)ConvertUtils.Convert(row[\"Age\"], CultureInfo.InvariantCulture, typeof(int)); // DBNull -> throws\n// after\nint? age = row[\"Age\"] == DBNull.Value ? (int?)null : Convert.ToInt32(row[\"Age\"]);","handlingStrategy":"validation","validationCode":"// Replace DBNull with null/default before converting into a value type.\nobject safe = value == DBNull.Value ? null : value;\nif (safe == null) {\n    if (ReflectionUtils.IsNullable(targetType)) return null;\n    if (targetType.IsValueType) return Activator.CreateInstance(targetType);\n}","typeGuard":"static bool AcceptsNull(Type t) => !t.IsValueType || System.Nullable.GetUnderlyingType(t) != null;","tryCatchPattern":"try { return ConvertUtils.Convert(value, culture, targetType); } catch (Exception ex) when (value == DBNull.Value && ex.Message.Contains(\"null\")) { return targetType.IsValueType ? Activator.CreateInstance(targetType) : null; }","preventionTips":["Map nullable DB columns to Nullable<T> or reference types.","Coerce DBNull to null at the data-access layer (row.Field<int?>(...)).","Never pass raw DBNull into a non-nullable struct target."],"tags":["conversion","nullable","dbnull","newtonsoft-json"],"analyzedSha":"4f73e74372445108d2c1bda37b36e6f5e43402e0","analyzedAt":"2026-08-07T06:10:08.596Z","schemaVersion":2},"datasetVersion":"2026-08-07T07:17:06.508Z"}