Skip to main content

How to Read a Custom Claim from a JWT in Java with JJWT Claims.get

· 8 min read
Jagdish Kumawat
Founder @ Dewiride

After JJWT verifies a token, claims.get("name", String.class) returns a claim's value as the type you ask for, or null when the token doesn't have the claim. JJWT converts between only a few simple types, so asking for a type the value isn't, such as an Integer for a string, throws a RequiredTypeException.

Syntax​

Syntax
Claims claims = Jwts.parser().verifyWith(key).build().parseSignedClaims(token).getPayload();
Type value = claims.get(name, Type.class);
PartWhat it does
parseSignedClaims(token).getPayload()Verifies the token's signature and expiry, then returns its claims.
claims.get(name, Type.class)Returns the claim's value as a Type, or null when the token doesn't have the claim.
nameThe claim's name.
Type.classThe type you expect, such as String.class, Integer.class or List.class.

JJWT's documentation for Claims.get: "Returns the JWTs claim (claimName) value as a requiredType instance, or null if not present." It goes on: "JJWT only converts simple String, Date, Long, Integer, Short and Byte types automatically. Anything more complex is expected to be already converted to your desired type by the JSON parser." For any other mismatch it throws a RequiredTypeException.

The Example​

The example signs a token with three custom claims, name, roles and albums, then verifies it and reads each one with the type it should have: a String, a List and an Integer. It also reads email, which the token doesn't have, and finally asks for name as an Integer, to show the exception.

Prerequisites​

  • A JDK and Maven. This guide uses OpenJDK 25.0.5.1 and Maven 3.10.2.

Step 1: Create the Project​

Create a folder named demo with this pom.xml. JJWT comes in three parts: jjwt-api for your code, and jjwt-impl and jjwt-jackson, which do the work while the program runs:

pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.example</groupId>
<artifactId>demo</artifactId>
<version>1.0.0</version>

<properties>
<maven.compiler.release>25</maven.compiler.release>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<jjwt.version>0.13.0</jjwt.version>
</properties>

<dependencyManagement>
<dependencies>
<!-- jjwt-jackson asks for Jackson 2.12.7.1. This makes Maven use the newest Jackson 2 instead. -->
<dependency>
<groupId>com.fasterxml.jackson</groupId>
<artifactId>jackson-bom</artifactId>
<version>2.23.0</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>

<dependencies>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-api</artifactId>
<version>${jjwt.version}</version>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-impl</artifactId>
<version>${jjwt.version}</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-jackson</artifactId>
<version>${jjwt.version}</version>
<scope>runtime</scope>
</dependency>
</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>3.7.0</version>
<configuration>
<mainClass>com.example.Main</mainClass>
</configuration>
</plugin>
</plugins>
</build>
</project>

Step 2: Write the Code​

Create src/main/java/com/example/Main.java:

Main.java, which signs a token with the claims name, roles and albums, verifies it, reads name as a String, roles as a List and albums as an Integer, prints them and the missing email claim, then catches the RequiredTypeException from reading name as an Integer.

src/main/java/com/example/Main.java
package com.example;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.RequiredTypeException;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.security.Keys;

import java.time.Duration;
import java.time.Instant;
import java.util.Date;
import java.util.List;
import javax.crypto.SecretKey;

public class Main {

public static void main(String[] args) {
// 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.
SecretKey key = Keys.hmacShaKeyFor(Decoders.BASE64.decode("C4iNOOORzmu+fnrPK29yq/9n92b/zf5mOs5KvOMaY64="));

String token = Jwts.builder()
.subject("ada")
.expiration(Date.from(Instant.now().plus(Duration.ofHours(1))))
.claim("name", "Ada")
.claim("roles", List.of("editor", "viewer"))
.claim("albums", 10)
.signWith(key)
.compact();
Claims claims = Jwts.parser().verifyWith(key).build().parseSignedClaims(token).getPayload();

String name = claims.get("name", String.class);
List<?> roles = claims.get("roles", List.class);
Integer albums = claims.get("albums", Integer.class);
System.out.println("name: " + name);
System.out.println("roles: " + roles);
System.out.println("albums: " + albums);
System.out.println("email: " + claims.get("email", String.class));

try {
claims.get("name", Integer.class);
} catch (RequiredTypeException e) {
System.out.println(e.getMessage());
}
}
}
  • claims.get("name", String.class) returns Ada as a String.
  • claims.get("roles", List.class) returns the JSON array as a Java List. List.class can't say what the list holds, so the variable is a List<?>, a list whose elements are of a type the code doesn't know.
  • claims.get("albums", Integer.class) returns the number as an Integer.
  • claims.get("email", String.class) asks for a claim the token doesn't have.
  • The try block asks for name as an Integer, and prints the message of the RequiredTypeException it catches.

Step 3: Run It​

In the demo folder:

Terminal
mvn -q compile exec:java
Output
name: Ada
roles: [editor, viewer]
albums: 10
email: null
Cannot convert existing claim value of type 'class java.lang.String' to desired type 'class java.lang.Integer'. JJWT only converts simple String, Date, Long, Integer, Short and Byte types automatically. Anything more complex is expected to be already converted to your desired type by the JSON Deserializer implementation. You may specify a custom Deserializer for a JwtParser with the desired conversion configuration via the JwtParserBuilder.deserializer() method. See https://github.com/jwtk/jjwt#custom-json-processor for more information. If using Jackson, you can specify custom claim POJO types as described in https://github.com/jwtk/jjwt#json-jackson-custom-types

A zsh terminal where mvn -q compile exec prints name: Ada, roles in square brackets, albums: 10 and email: null, then the RequiredTypeException message that a java.lang.String can't be converted to a java.lang.Integer.

-q keeps Maven quiet, compile builds the program and exec:java runs it. The command is the same in zsh, bash and PowerShell.

What Happened​

  • name, roles and albums came back as a String, a List and an Integer. The roles print in square brackets because they're a Java list.
  • email is null, because the token has no email claim. A missing claim gives null whatever type you ask for.
  • claims.get("name", Integer.class) threw a RequiredTypeException. Ada is a string, and JJWT doesn't turn strings into numbers.

The message tells you to configure a custom deserializer "via the JwtParserBuilder.deserializer() method", but JwtParserBuilder in JJWT 0.13.0 has no such method. The method is json(Deserializer), which is the one the documentation of Claims.get names. I reported the wrong name in the message as jwtk/jjwt#1089.

I also checked which conversions JJWT makes, with the claims in other tokens:

The claim in the tokenAsked forResult
10Integer, Long, Short or Byte10, as that type
10Double or StringRequiredTypeException
5000000000IntegerRequiredTypeException: Claim 'big' value is too large or too small to be represented as a java.lang.Integer instance (would cause numeric overflow).
5000000000Long5000000000
2.5Double2.5
2.5IntegerRequiredTypeException
"10", a stringIntegerRequiredTypeException: JJWT doesn't read numbers out of text
["editor","viewer"]List, Collection or ObjectAn ArrayList
["editor","viewer"]String or String[]RequiredTypeException
{"albums":10}MapA LinkedHashMap
trueBooleantrue
A claim the token doesn't haveAny typenull

Common Mistakes​

MistakeWhat happensDo this instead
Asking for a type the claim isn't, such as Integer for the string "10"RequiredTypeExceptionAsk for the JSON type the token holds
Asking for Integer for a number that can be largeRequiredTypeException with would cause numeric overflowAsk for Long
Asking for String[] for an arrayRequiredTypeExceptionAsk for List
Using a claim's value before checking it for nullA token without that claim gives null, and the code that uses it failsTreat null as a missing claim first

Troubleshooting​

SymptomLikely causeFix
io.jsonwebtoken.RequiredTypeException: Cannot convert existing claim value of type 'class java.lang.String' to desired type 'class java.lang.Integer'. …, and the message goes onThe claim's value isn't the type you asked forAsk for its JSON type, or read it with claims.get(name) and check it with instanceof
RequiredTypeException: Claim 'big' value is too large or too small to be represented as a java.lang.Integer instance (would cause numeric overflow).The number doesn't fit in an IntegerAsk for Long
The message points to JwtParserBuilder.deserializer(), which doesn't existThe message names a method JJWT doesn't haveUse json(Deserializer) on the parser builder

FAQ​

What does claims.get return without a type?​

An Object that holds what JJWT's JSON parser made: a java.lang.Integer for albums, a java.util.ArrayList for roles and a java.util.LinkedHashMap for an object. Check it with instanceof before you use it.

Can JJWT read a claim into a class of my own?​

The README section Parsing of Custom Claim Types shows how: "If you need to deserialize other types you can configure the JacksonDeserializer by passing a Map of claim names to types in through a constructor." This post sticks to the types JJWT converts by itself.

Conclusion​

claims.get(name, Type.class) reads a claim as the type you expect, and gives null when the claim is missing. Ask for the JSON type the token holds: String for text, Integer or Long for numbers, List for arrays and Map for objects. JJWT converts between only a few simple types, and throws a RequiredTypeException for anything else.

Additional Resources​