JamesNK/Newtonsoft.Json · error · ArgumentException

Value must be positive.

Error message

Value must be positive.

What it means

Thrown by the JsonSerializerSettings.MaxDepth setter when assigning a value less than or equal to zero. Like the reader/serializer MaxDepth, it bounds nesting depth for safety against deep/malicious JSON; non-positive values are invalid and rejected with ArgumentException. Null disables the limit.

Source

Thrown at Src/Newtonsoft.Json/JsonSerializerSettings.cs:344

            {
                _dateFormatString = value;
                _dateFormatStringSet = true;
            }
        }

        /// <summary>
        /// Gets or sets the maximum depth allowed when reading JSON. Reading past this depth will throw a <see cref="JsonReaderException"/>.
        /// A null value means there is no maximum.
        /// The default value is <c>64</c>.
        /// </summary>
        public int? MaxDepth
        {
            get => _maxDepthSet ? _maxDepth : DefaultMaxDepth;
            set
            {
                if (value <= 0)
                {
                    throw new ArgumentException("Value must be positive.", nameof(value));
                }

                _maxDepth = value;
                _maxDepthSet = true;
            }
        }

        /// <summary>
        /// Indicates how JSON text output is formatted.
        /// The default value is <see cref="Json.Formatting.None" />.
        /// </summary>
        public Formatting Formatting
        {
            get => _formatting ?? DefaultFormatting;
            set => _formatting = value;
        }

        /// <summary>

View on GitHub (pinned to 4f73e74372)

Solutions

  1. Use a positive integer (default is 64).
  2. Pass null to disable the cap explicitly.
  3. Validate config before assignment: settings.MaxDepth = (depth > 0) ? depth : null;.

Example fix

// before
settings.MaxDepth = 0;

// after
settings.MaxDepth = 64; // or null
Defensive patterns

Strategy: validation

Validate before calling

settings.MaxDepth = configuredDepth switch
{
    int d when d > 0 => d,
    _ => (int?)null,
};

Type guard

static bool IsValidMaxDepth(int? v) => v is null or > 0;

Prevention

When it happens

Trigger: Setting settings.MaxDepth = 0 or negative; sourcing MaxDepth from config/env/user input without validation; arithmetic that yields a non-positive value.

Common situations: Appsettings/environment values parsed to 0; passing 0 intending default; conditional logic that subtracts depth.

Related errors


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