JamesNK/Newtonsoft.Json · error · ArgumentException
Value must be positive.
Error message
Value must be positive.
What it means
Thrown by the JsonSerializer.MaxDepth setter when assigning a value less than or equal to zero. MaxDepth bounds JSON nesting depth to prevent stack overflows and denial-of-service via pathological/deeply-nested input; a non-positive bound is invalid, so the setter rejects it with ArgumentException. Null means no limit and is allowed.
Source
Thrown at Src/Newtonsoft.Json/JsonSerializer.cs:528
public virtual CultureInfo Culture
{
get => _culture ?? JsonSerializerSettings.DefaultCulture;
set => _culture = value;
}
/// <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 virtual int? MaxDepth
{
get => _maxDepth;
set
{
if (value <= 0)
{
throw new ArgumentException("Value must be positive.", nameof(value));
}
_maxDepth = value;
_maxDepthSet = true;
}
}
/// <summary>
/// Gets a value indicating whether there will be a check for additional JSON content after deserializing an object.
/// The default value is <c>false</c>.
/// </summary>
/// <value>
/// <c>true</c> if there will be a check for additional JSON content after deserializing an object; otherwise, <c>false</c>.
/// </value>
public virtual bool CheckAdditionalContent
{
get => _checkAdditionalContent ?? JsonSerializerSettings.DefaultCheckAdditionalContent;
set => _checkAdditionalContent = value;View on GitHub (pinned to 4f73e74372)
Solutions
- Assign a positive integer (64 is the library default).
- Pass null to explicitly disable the cap.
- Validate first: if (depth is int d && d > 0) serializer.MaxDepth = d;.
Example fix
// before serializer.MaxDepth = 0; // after serializer.MaxDepth = 64; // or null for no limit
Defensive patterns
Strategy: validation
Validate before calling
if (configuredDepth is int d && d > 0)
{
serializer.MaxDepth = d;
} Type guard
static bool IsValidMaxDepth(int? v) => v is null or > 0;
Prevention
- Use 64 (default) or another positive value; use null for no cap.
- Validate config at load time and fail loudly.
- Do not derive MaxDepth from untrusted arithmetic without clamping.
When it happens
Trigger: Setting serializer.MaxDepth = 0 or a negative number; feeding MaxDepth from unvalidated config or arithmetic that can go non-positive.
Common situations: Reading MaxDepth from appsettings/environment without bounds checking; passing 0 intending 'default'; subtractive arithmetic producing negatives.
Related errors
AI-assisted analysis of JamesNK/Newtonsoft.Json@4f73e74372 (2026-08-07).
Data as JSON: /api/errors/2a54cddfc589bbaf.
Report an issue: GitHub.