JamesNK/Newtonsoft.Json · error · Exception

Can not convert null {0} into non-nullable {1}.

Error message

Can not convert null {0} into non-nullable {1}.

What it means

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.

Source

Thrown at Src/Newtonsoft.Json/Utilities/ConvertUtils.cs:389

#region TryConvert
        internal enum ConvertResult
        {
            Success = 0,
            CannotConvertNull = 1,
            NotInstantiableType = 2,
            NoValidConversion = 3
        }

        [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
        [RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
        public static object Convert(object initialValue, CultureInfo culture, Type targetType)
        {
            switch (TryConvertInternal(initialValue, culture, targetType, out object? value))
            {
                case ConvertResult.Success:
                    return value!;
                case ConvertResult.CannotConvertNull:
                    throw new Exception("Can not convert null {0} into non-nullable {1}.".FormatWith(CultureInfo.InvariantCulture, initialValue.GetType(), targetType));
                case ConvertResult.NotInstantiableType:
                    throw new ArgumentException("Target type {0} is not a value type or a non-abstract class.".FormatWith(CultureInfo.InvariantCulture, targetType), nameof(targetType));
                case ConvertResult.NoValidConversion:
                    throw new InvalidOperationException("Can not convert from {0} to {1}.".FormatWith(CultureInfo.InvariantCulture, initialValue.GetType(), targetType));
                default:
                    throw new InvalidOperationException("Unexpected conversion result.");
            }
        }

        [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)]
        [RequiresDynamicCode(MiscellaneousUtils.AotWarning)]
        private static bool TryConvert(object? initialValue, CultureInfo culture, Type targetType, out object? value)
        {
            try
            {
                if (TryConvertInternal(initialValue, culture, targetType, out value) == ConvertResult.Success)
                {
                    return true;

View on GitHub (pinned to 4f73e74372)

Solutions

  1. Make the target type nullable (int? / Nullable<T>) or a reference type.
  2. Replace DBNull.Value with null (or a sensible default) before invoking Convert.
  3. Filter DBNull at the data-access layer: row.Field<int?>("Col") ?? default.
  4. Use a custom JsonConverter that maps DBNull to default(T).

Example fix

// before
int age = (int)ConvertUtils.Convert(row["Age"], CultureInfo.InvariantCulture, typeof(int)); // DBNull -> throws
// after
int? age = row["Age"] == DBNull.Value ? (int?)null : Convert.ToInt32(row["Age"]);
Defensive patterns

Strategy: validation

Validate before calling

// Replace DBNull with null/default before converting into a value type.
object safe = value == DBNull.Value ? null : value;
if (safe == null) {
    if (ReflectionUtils.IsNullable(targetType)) return null;
    if (targetType.IsValueType) return Activator.CreateInstance(targetType);
}

Type guard

static bool AcceptsNull(Type t) => !t.IsValueType || System.Nullable.GetUnderlyingType(t) != null;

Try / catch

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; }

Prevention

When it happens

Trigger: 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.

Common situations: 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.

Related errors


AI-assisted analysis of JamesNK/Newtonsoft.Json@4f73e74372 (2026-08-07). Data as JSON: /api/errors/354e484927e3cf72. Report an issue: GitHub.