Skip to main content

Fixed: "IDX11025: Cannot serialize object of type: 'Plan' into property: 'plan'" in .NET C#

· 10 min read
Jagdish Kumawat
Founder @ Dewiride

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:

Terminal
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:

Program.cs
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:

Terminal
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:

Output
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

A zsh terminal where dotnet run stops with Unhandled exception. System.ArgumentException: IDX11025: Cannot serialize object of type: 'Plan' into property: 'plan', thrown from JsonSerializerPrimitives.WriteObject inside JsonWebTokenHandler.CreateToken.

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:

Output
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:

The fixed Program.cs: JsonSerializerOptions with the SnakeCaseLower naming policy, the plan claim set to JsonSerializer.SerializeToElement of the Plan record, then the claim read back with GetPayloadValue of JsonElement and turned into a Plan again with JsonSerializer.Deserialize.

Program.cs
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 a JsonElement, a JSON object the handler can write.
  • json sets the naming policy. JsonNamingPolicy.SnakeCaseLower is, in Microsoft Learn's words, "the naming policy for lowercase snake-casing", so OrderLimit becomes order_limit. Without it, the claim keeps the C# names: {"Name":"pro","OrderLimit":500}.
  • GetPayloadValue<JsonElement>("plan") reads the claim back as a JsonElement, and JsonSerializer.Deserialize<Plan> turns it into a Plan again. Pass it the same options, so that order_limit finds its way back to OrderLimit.
  • ReadJsonWebToken reads a token without checking its signature. It's here only to show what the token carries. An API reads the claim from the token that ValidateTokenAsync returns, 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​

Terminal
dotnet run
Output
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJ1c2VyLTQyIiwicGxhbiI6eyJuYW1lIjoicHJvIiwib3JkZXJfbGltaXQiOjUwMH0sImV4cCI6MTc5NjI4OTU5NiwiaWF0IjoxNzk2Mjg1OTk2LCJuYmYiOjE3OTYyODU5OTZ9.66xd6rbQItxfgXtGXBX392-dgOXp-URyiEnlNxXDgAg
{"name":"pro","order_limit":500}
Plan { Name = pro, OrderLimit = 500 }

The same app after the fix: dotnet run prints a token, the plan claim as the JSON object with name pro and order_limit 500, and the record read back as Plan with Name pro and 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​

MistakeWhat happensDo this instead
Turning the object into a string with JsonSerializer.SerializeThe claim becomes a JSON string with escaped quotes, "plan":"{\"name\":\"pro\",\"order_limit\":500}", not an objectUse 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 withNo 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 valueIDX11025 with a type name like ListSelectIteratorCall ToArray() or ToList() first
Trusting a claim read with ReadJsonWebTokenNothing checks the signature, so anyone could have written itRead claims from the token that ValidateTokenAsync returns

Troubleshooting​

SymptomLikely causeFix
IDX11025: Cannot serialize object of type: 'Plan' into property: 'plan'.A claim value is a class, record or anonymous objectJsonSerializer.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 ownRead a JsonElement and deserialize it
The claim's properties are Name and OrderLimit, not name and order_limitNo naming policySet PropertyNamingPolicy in JsonSerializerOptions
The record comes back with empty valuesDifferent options for writing and readingUse 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​