JamesNK/Newtonsoft.Json · error · ArgumentException
Object must be of type Guid.
Error message
Object must be of type Guid.
What it means
Thrown by JValue.CompareTo when the token's JSON type is JTokenType.Guid and the operand is not a Guid. Two Guid JValues are compared with Guid.CompareTo; a non-Guid operand has no ordering relationship, so CompareTo throws ArgumentException. This mirrors the type-strict comparison behaviour of all primitive JValue token types.
Source
Thrown at Src/Newtonsoft.Json/Linq/JValue.cs:374
}
return offsetA.CompareTo(offsetB);
}
#endif
case JTokenType.Bytes:
if (!(objB is byte[] bytesB))
{
throw new ArgumentException("Object must be of type byte[].");
}
byte[]? bytesA = objA as byte[];
MiscellaneousUtils.Assert(bytesA != null);
return MiscellaneousUtils.ByteArrayCompare(bytesA!, bytesB);
case JTokenType.Guid:
if (!(objB is Guid))
{
throw new ArgumentException("Object must be of type Guid.");
}
Guid guid1 = (Guid)objA;
Guid guid2 = (Guid)objB;
return guid1.CompareTo(guid2);
case JTokenType.Uri:
Uri? uri2 = objB as Uri;
if (uri2 == null)
{
throw new ArgumentException("Object must be of type Uri.");
}
Uri uri1 = (Uri)objA;
return Comparer<string>.Default.Compare(uri1.ToString(), uri2.ToString());
case JTokenType.TimeSpan:
if (!(objB is TimeSpan))View on GitHub (pinned to 4f73e74372)
Solutions
- Convert the operand to Guid first: token.CompareTo(Guid.Parse(text)).
- Use token.Value<Guid>() and compare the resulting Guid values with the standard Guid comparer.
- Type-check the operand before calling CompareTo.
Example fix
// before
int c = guidToken.CompareTo("d3b0c1f2-...");
// after
int c = guidToken.CompareTo(Guid.Parse("d3b0c1f2-...")); Defensive patterns
Strategy: type-guard
Validate before calling
if (other is Guid g) { int c = guidToken.CompareTo(g); } Type guard
static bool IsGuid(object? o) => o is Guid;
Try / catch
try { int c = token.CompareTo(other); } catch (ArgumentException ex) when (ex.Message.Contains("Guid")) { /* parse string to Guid */ } Prevention
- Parse string operands to Guid before comparing Guid JValues.
- Standardize on Guid for GUID-typed fields.
- Type-check operands in heterogeneous comparisons.
When it happens
Trigger: Comparing a Guid JValue against a string like token.CompareTo("00000000-...") instead of a Guid instance, or against an int/other primitive. Triggered during sorting or equality checks inside JObject/JArray operations.
Common situations: Treating a GUID field as a string in comparison logic; deserializing database uniqueidentifier columns then comparing against string literals in LINQ-to-JSON queries.
Related errors
- Object must be of type byte[].
- Object must be of type Uri.
- Object must be of type TimeSpan.
- Could not determine JSON object type for type {0}.
- Cannot access child value on {0}.
AI-assisted analysis of JamesNK/Newtonsoft.Json@4f73e74372 (2026-08-07).
Data as JSON: /api/errors/89c2468daf187d2c.
Report an issue: GitHub.