JamesNK/Newtonsoft.Json · error · ArgumentException
Value must be positive.
Error message
Value must be positive.
What it means
Thrown by the JsonReader.MaxDepth setter when assigning a value less than or equal to zero. MaxDepth caps nesting depth to defend against deeply nested or malicious JSON (stack overflow / denial of service); a non-positive cap is meaningless, so the setter rejects it with ArgumentException. Null is permitted and means no limit.
Source
Thrown at Src/Newtonsoft.Json/JsonReader.cs:240
public string? DateFormatString
{
get => _dateFormatString;
set => _dateFormatString = 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 int? MaxDepth
{
get => _maxDepth;
set
{
if (value <= 0)
{
throw new ArgumentException("Value must be positive.", nameof(value));
}
_maxDepth = value;
}
}
/// <summary>
/// Gets the type of the current JSON token.
/// </summary>
public virtual JsonToken TokenType => _tokenType;
/// <summary>
/// Gets the text value of the current JSON token.
/// </summary>
public virtual object? Value => _value;
/// <summary>
/// Gets the .NET type for the current JSON token.View on GitHub (pinned to 4f73e74372)
Solutions
- Use a positive integer (e.g. 64, the library default) for MaxDepth.
- Pass null to explicitly disable the depth cap rather than 0.
- Validate config-driven values before assignment: if (depth is > 0 int d) reader.MaxDepth = d;.
Example fix
// before reader.MaxDepth = 0; // after reader.MaxDepth = 64; // or leave null for no limit
Defensive patterns
Strategy: validation
Validate before calling
if (configuredDepth is int d && d > 0)
{
reader.MaxDepth = d;
} Type guard
static bool IsValidMaxDepth(int? v) => v is null or > 0;
Prevention
- Treat null as 'no limit', not 0.
- Bound config values: clamp to a sane positive default (e.g. 64).
- Validate at config load and fail loudly rather than at serialization time.
When it happens
Trigger: Setting reader.MaxDepth = 0, reader.MaxDepth = -1, or computing MaxDepth from user/config input that can be zero or negative.
Common situations: Loading MaxDepth from configuration/environment without validating; passing 0 intending 'use default'; arithmetic that subtracts and yields a negative.
Related errors
AI-assisted analysis of JamesNK/Newtonsoft.Json@4f73e74372 (2026-08-07).
Data as JSON: /api/errors/32235dab29dab8c0.
Report an issue: GitHub.