Fixed: "IDX11025: Cannot serialize object of type: 'Plan' into property: 'plan'" in .NET C#
JsonWebTokenHandler.CreateToken stopped with IDX11025: Cannot serialize object of type: 'Plan' into property: 'plan'. when one of my custom claims held a C# record. The library writes a JWT's payload itself and knows only a fixed list of types. A record isn't on it, but a JsonElement is, and JsonSerializer.SerializeToElement turns the record into one.
What I Was Doing
I was writing the C# part of Custom Claims, a tutorial in which a sign-in service puts a user's plan in a token as a JSON object: the plan's name and the most the user may order. A record looked like the natural C# type for it. To show the problem on its own, I repeated it in a new console app with the .NET 10.0.404 SDK and Microsoft.IdentityModel.JsonWebTokens 8.25.0:
dotnet new console -o plan-token
cd plan-token
dotnet package add Microsoft.IdentityModel.JsonWebTokens
Then I replaced Program.cs with code that creates a token with two claims, sub and plan, where plan is a Plan record:
using Microsoft.IdentityModel.JsonWebTokens;
using Microsoft.IdentityModel.Tokens;
// The signing key: 32 random bytes, written as base64.
// It's in the code only for this example; a real app loads it from its configuration.
var key = Convert.FromBase64String("C4iNOOORzmu+fnrPK29yq/9n92b/zf5mOs5KvOMaY64=");
var descriptor = new SecurityTokenDescriptor
{
Claims = new Dictionary<string, object>
{
["sub"] = "user-42",
["plan"] = new Plan("pro", 500),
},
SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256),
};
string token = new JsonWebTokenHandler().CreateToken(descriptor);
Console.WriteLine(token);
record Plan(string Name, int OrderLimit);
And ran it:
dotnet run
What I Expected
A token whose payload held the plan as a JSON object, such as "plan":{"Name":"pro","OrderLimit":500}.
What I Got
No token. CreateToken threw an exception, and the program stopped:
Unhandled exception. System.ArgumentException: IDX11025: Cannot serialize object of type: 'Plan' into property: 'plan'.
at Microsoft.IdentityModel.Tokens.Json.JsonSerializerPrimitives.WriteObject(Utf8JsonWriter& writer, String key, Object obj)
at Microsoft.IdentityModel.JsonWebTokens.JsonWebTokenHandler.WriteJwsPayload(Utf8JsonWriter& writer, SecurityTokenDescriptor tokenDescriptor, Boolean setDefaultTimesOnTokenCreation, Int32 tokenLifetimeInMinutes)
at Microsoft.IdentityModel.JsonWebTokens.JsonWebTokenHandler.CreateToken(SecurityTokenDescriptor tokenDescriptor, Boolean setdefaultTimesOnTokenCreation, Int32 tokenLifetimeInMinutes)
at Microsoft.IdentityModel.JsonWebTokens.JsonWebTokenHandler.CreateToken(SecurityTokenDescriptor tokenDescriptor)
at Program.<Main>$(String[] args) in /Users/Shared/you/plan-token/Program.cs:line 17

What I Checked
The documentation of the property I filled. Microsoft Learn describes SecurityTokenDescriptor.Claims as "the Dictionary<TKey,TValue> which represents the claims that will be used when creating a security token". Its type is IDictionary<string, object>, so the compiler accepts any value. The page says nothing about which values the handler can write.
Where the exception came from. The stack trace starts in JsonSerializerPrimitives.WriteObject. I read that method in the library's source code at version 8.25.0. It writes null, string, long, int, bool, DateTime, byte[], any IDictionary, any IList, JsonElement, JsonNode, double, decimal, float and Guid. For anything else it throws IDX11025.
Whether it's only records. It isn't. A class of my own failed the same way, and so did an anonymous object and the result of a LINQ Select:
IDX11025: Cannot serialize object of type: '<>f__AnonymousType0`1[System.String]' into property: 'plan'.
IDX11025: Cannot serialize object of type: 'System.Linq.Enumerable+ListSelectIterator`2[System.String,System.String]' into property: 'plan'.
What the library's maintainers say. IdentityModel's own notes on version 7 explain the change behind it: "Previously, IdentityModel used Newtonsoft for JSON serialization, but now it uses System.Text.Json." In issue #2455, a team whose own class worked as a claim value in version 6.35.0 lost that after updating to 7.2.0. A maintainer answered that the library had switched to System.Text.Json internally and pointed to JsonSerializer.SerializeToElement, with an example that reads the claim back as a JsonElement.
Why It Happens
JsonWebTokenHandler doesn't hand your claims to a JSON serializer. It writes the payload itself, one claim at a time, and checks each value against that list of types. A record isn't a dictionary, a list or one of the simple types, so the handler has no way to know how to write it. It throws instead of guessing. Older versions used Newtonsoft.Json, which wrote any object, which is why code like this can break on an update.
The Fix
Turn the object into a JsonElement before it goes into the claims. Microsoft Learn describes JsonSerializer.SerializeToElement as a method that "Converts the provided value into a JsonElement", and WriteObject writes a JsonElement exactly as it is. Here is the complete Program.cs with the fix, which also reads the claim back:

using System.Text.Json;
using Microsoft.IdentityModel.JsonWebTokens;
using Microsoft.IdentityModel.Tokens;
// The signing key: 32 random bytes, written as base64.
// It's in the code only for this example; a real app loads it from its configuration.
var key = Convert.FromBase64String("C4iNOOORzmu+fnrPK29yq/9n92b/zf5mOs5KvOMaY64=");
// Write the record's properties as name and order_limit.
var json = new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.SnakeCaseLower };
var descriptor = new SecurityTokenDescriptor
{
Claims = new Dictionary<string, object>
{
["sub"] = "user-42",
// IdentityModel writes a JsonElement as it is, so turn the record into one first.
["plan"] = JsonSerializer.SerializeToElement(new Plan("pro", 500), json),
},
SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256),
};
var handler = new JsonWebTokenHandler();
string token = handler.CreateToken(descriptor);
Console.WriteLine(token);
// Read the claim back and turn it into a Plan again.
JsonElement planClaim = handler.ReadJsonWebToken(token).GetPayloadValue<JsonElement>("plan");
Console.WriteLine(planClaim);
Plan? plan = JsonSerializer.Deserialize<Plan>(planClaim, json);
Console.WriteLine(plan);
record Plan(string Name, int OrderLimit);
JsonSerializer.SerializeToElement(new Plan("pro", 500), json)turns the record into aJsonElement, a JSON object the handler can write.jsonsets the naming policy.JsonNamingPolicy.SnakeCaseLoweris, in Microsoft Learn's words, "the naming policy for lowercase snake-casing", soOrderLimitbecomesorder_limit. Without it, the claim keeps the C# names:{"Name":"pro","OrderLimit":500}.GetPayloadValue<JsonElement>("plan")reads the claim back as aJsonElement, andJsonSerializer.Deserialize<Plan>turns it into aPlanagain. Pass it the same options, so thatorder_limitfinds its way back toOrderLimit.ReadJsonWebTokenreads a token without checking its signature. It's here only to show what the token carries. An API reads the claim from the token thatValidateTokenAsyncreturns, after the token has been verified.
If the reading side doesn't need your type, there's a second fix: build the value from types the handler writes. A Dictionary<string, object> becomes a JSON object and a string[] becomes a JSON array. The Custom Claims tutorial builds its plan claim that way.
After the Fix
dotnet run
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJ1c2VyLTQyIiwicGxhbiI6eyJuYW1lIjoicHJvIiwib3JkZXJfbGltaXQiOjUwMH0sImV4cCI6MTc5NjI4OTU5NiwiaWF0IjoxNzk2Mjg1OTk2LCJuYmYiOjE3OTYyODU5OTZ9.66xd6rbQItxfgXtGXBX392-dgOXp-URyiEnlNxXDgAg
{"name":"pro","order_limit":500}
Plan { Name = pro, OrderLimit = 500 }

The handler created the token. The plan claim came back as the JSON object {"name":"pro","order_limit":500}, and Deserialize turned it into the same record. The payload also holds exp, iat and nbf, because JsonWebTokenHandler adds those times by default.
Common Mistakes
| Mistake | What happens | Do this instead |
|---|---|---|
Turning the object into a string with JsonSerializer.Serialize | The claim becomes a JSON string with escaped quotes, "plan":"{\"name\":\"pro\",\"order_limit\":500}", not an object | Use SerializeToElement, which keeps it a JSON object |
Reading the claim with GetPayloadValue<Plan> | It throws IDX14305: Unable to convert the 'plan' json property to the following type: 'Plan'. | Read a JsonElement, then JsonSerializer.Deserialize<Plan> |
| Deserializing without the options you serialized with | No error, but an empty record: Plan { Name = , OrderLimit = 0 } | Pass the same JsonSerializerOptions both ways |
| Passing the result of a LINQ query as a claim value | IDX11025 with a type name like ListSelectIterator | Call ToArray() or ToList() first |
Trusting a claim read with ReadJsonWebToken | Nothing checks the signature, so anyone could have written it | Read claims from the token that ValidateTokenAsync returns |
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
IDX11025: Cannot serialize object of type: 'Plan' into property: 'plan'. | A claim value is a class, record or anonymous object | JsonSerializer.SerializeToElement, or a Dictionary<string, object> |
IDX14305: Unable to convert the 'plan' json property to the following type: 'Plan'. | GetPayloadValue<T> with a type of your own | Read a JsonElement and deserialize it |
The claim's properties are Name and OrderLimit, not name and order_limit | No naming policy | Set PropertyNamingPolicy in JsonSerializerOptions |
| The record comes back with empty values | Different options for writing and reading | Use the same JsonSerializerOptions both ways |
FAQ
Which claim values does JsonWebTokenHandler accept?
In version 8.25.0: null, string, long, int, bool, DateTime, byte[], any IDictionary, any IList, JsonElement, JsonNode, double, decimal, float and Guid. Dictionaries and lists may hold those types too.
Does JwtSecurityTokenHandler behave the same way?
It did for the person who opened issue #2397: an anonymous object in a claim stopped JwtSecurityTokenHandler with the same message after the update to version 7. I tested only JsonWebTokenHandler. Microsoft Learn calls JwtSecurityToken "the previous generation of JSON Web Token (JWT) implementation", and since ASP.NET Core 8.0 its authentication handlers use the newer JsonWebToken by default.
Can I keep using my record type?
Yes. SerializeToElement on the way in and Deserialize<T> on the way out keep the record in your code, and only the token holds plain JSON.
Conclusion
IDX11025: Cannot serialize object of type means a claim value isn't one of the types IdentityModel writes. Since version 7, the library writes JSON itself with System.Text.Json and no longer serializes objects of your own. Turn the object into a JsonElement with JsonSerializer.SerializeToElement, or build the value from a dictionary, and the token is created.
Additional Resources
- SecurityTokenDescriptor.Claims, on Microsoft Learn.
- JsonSerializer.SerializeToElement and JsonNamingPolicy.SnakeCaseLower, on Microsoft Learn.
- JsonSerializerPrimitives.WriteObject, the method that throws IDX11025, in IdentityModel 8.25.0.
- Issue #2455, where a maintainer shows
SerializeToElementfor a custom claim.
Related
- Custom Claims, the JWT tutorial where this came up.
- How to Create a .NET C# Console App with dotnet new console
- How to Add, Update and Remove a NuGet Package with the dotnet CLI
