JamesNK/Newtonsoft.Json · error · JsonException

Unexpected type code '{0}' for type '{1}'.

Error message

Unexpected type code '{0}' for type '{1}'.

What it means

Thrown by JsonSchemaGenerator.Generate when mapping a .NET type to a JSON Schema type. The generator switches on the type's PrimitiveTypeCode (obtained via ConvertUtils.GetTypeCode) and the value landed in the unhandled 'default' branch (line 526), meaning the type could not be classified into any known JSON Schema category (boolean, integer, float, string, null). It is effectively an internal signal that the schema generator does not know how to represent the given type.

Source

Thrown at Src/Newtonsoft.Json/Schema/JsonSchemaGenerator.cs:526

                    return schemaType | JsonSchemaType.Integer;
                case PrimitiveTypeCode.Single:
                case PrimitiveTypeCode.Double:
                case PrimitiveTypeCode.Decimal:
                    return schemaType | JsonSchemaType.Float;
                // convert to string?
                case PrimitiveTypeCode.DateTime:
#if HAVE_DATE_TIME_OFFSET
                case PrimitiveTypeCode.DateTimeOffset:
#endif
                    return schemaType | JsonSchemaType.String;
                case PrimitiveTypeCode.String:
                case PrimitiveTypeCode.Uri:
                case PrimitiveTypeCode.Guid:
                case PrimitiveTypeCode.TimeSpan:
                case PrimitiveTypeCode.Bytes:
                    return schemaType | JsonSchemaType.String;
                default:
                    throw new JsonException("Unexpected type code '{0}' for type '{1}'.".FormatWith(CultureInfo.InvariantCulture, typeCode, type));
            }
        }
    }
}

View on GitHub (pinned to 4f73e74372)

Solutions

  1. Do not generate a JSON schema for the offending type; serialize it directly with JsonConvert.SerializeObject instead of JsonSchemaGenerator.Generate.
  2. Upgrade Newtonsoft.Json to a version that recognizes the primitive type code returned for your type.
  3. Map the problem type to a known schema manually (e.g. JsonSchemaType.String) rather than letting the generator infer it.
  4. If the type is one you control, ensure its primitive representation maps to a handled code, or register a custom contract/converter so the generator sees a supported type.

Example fix

// before
var schema = generator.Generate(typeof(MyExoticType)); // throws Unexpected type code

// after
var schema = generator.Generate(typeof(MyExoticType), false);
// or avoid schema generation; just serialize the value as a string
var json = JsonConvert.SerializeObject(myExoticType.ToString());
Defensive patterns

Strategy: validation

Validate before calling

// Before generating a schema, confirm the type maps to a known schema category.
var typeCode = Newtonsoft.Json.Utilities.ConvertUtils.GetTypeCode(typeof(T));
var known = typeCode == PrimitiveTypeCode.Empty || typeCode == PrimitiveTypeCode.Object
    || typeCode == PrimitiveTypeCode.Boolean || typeCode == PrimitiveTypeCode.Char
    || typeCode == PrimitiveTypeCode.String || typeCode == PrimitiveTypeCode.Uri
    || typeCode == PrimitiveTypeCode.Guid || typeCode == PrimitiveTypeCode.TimeSpan
    || typeCode == PrimitiveTypeCode.Bytes || typeCode == PrimitiveTypeCode.DateTime
    || typeCode == PrimitiveTypeCode.DBNull
    || new[] { PrimitiveTypeCode.SByte, PrimitiveTypeCode.Byte, PrimitiveTypeCode.Int16,
        PrimitiveTypeCode.UInt16, PrimitiveTypeCode.Int32, PrimitiveTypeCode.UInt32,
        PrimitiveTypeCode.Int64, PrimitiveTypeCode.UInt64, PrimitiveTypeCode.BigInteger,
        PrimitiveTypeCode.Single, PrimitiveTypeCode.Double, PrimitiveTypeCode.Decimal }.Contains(typeCode);
if (!known) throw new InvalidOperationException($"Cannot generate schema for type code {typeCode}.");

Type guard

static bool HasKnownSchemaTypeCode(Type t)
{
    var code = Newtonsoft.Json.Utilities.ConvertUtils.GetTypeCode(t);
    return code != PrimitiveTypeCode.Empty; // refine with the set above as needed
}

Try / catch

try { var schema = generator.Generate(type); }
catch (JsonException ex) when (ex.Message.StartsWith("Unexpected type code"))
{
    // fall back to a string schema or skip schema generation
}

Prevention

When it happens

Trigger: Calling JsonSchemaGenerator.Generate(typeof(T)) where T resolves to a PrimitiveTypeCode that none of the handled cases cover (the switch handles Empty, Object, DBNull, Boolean, Char, the integer codes, the float codes, DateTime, DateTimeOffset, String, Uri, Guid, TimeSpan, Bytes). Any type whose code falls outside that set hits the default branch.

Common situations: Exotic CLR types (COM/dynamic interop types, types exposed by a newer runtime whose primitive code Json.NET in this version does not enumerate), or types whose reflection-reported type code is unexpected. Rare in normal DTO serialization; seen when generating schemas for unusual framework types.

Related errors


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