Vishal Gajera
Vishal Gajera

Reputation: 4207

How to convert from io.jsonwebtoken.Claims to java.util.Map<String,Object>?

I am working with JWT token using io.jsonwebtoken maven dependency.

I am able to create a JWT token with custom payloads successfully.

Now while i am going to parse it, I need Map<String, Object> object which has all those custom payloads which are added at the time of creation, but unfortunately i am unable to complete it.

I am using following code to parse it,

JwtParser parser = Jwts.parser();
Claims claims = parser
                .setSigningKey(DatatypeConverter.parseBase64Binary(SIGN_KEY))
                        .parseClaimsJws(jwt).getBody();

Now, I have io.jsonwebtoken.Claims , but don't know how to convert this io.jsonwebtoken.Claims to java.util.Map<String,Object>

However I try with this to know(almost looks similar which i want) :-

System.out.println(claims.toString()); -> this is correctly prints whole custom payloads.

But i need Map<String,Object>

Any help will be appreciate..!!

Upvotes: 2

Views: 12905

Answers (2)

Alex S.
Alex S.

Reputation: 81

io.jsonwebtoken.Claims extends java.util.Map<String, Object>.

io.jsonwebtoken.impl.DefaultClaims, the only provided implementation of Claims, is their implementation of Map, which decorates LinkedHashMap<String, Object> and adds a couple of methods.

So you should do nothing to convert to Map, because it is already Map<String, Object>. If you'd like to get rid off their custom methods and convert Claims to HashMap, the shortest way is just pass Claims to the HashMap's constructor. It does the same as you did manually.

Claims claims = ...; 

Map<String, Object> expectedMap = new HashMap<>(claims);

Upvotes: 4

Vishal Gajera
Vishal Gajera

Reputation: 4207

Finally, i got the answer by listening my own - don't stop till get the answer,

public Map<String, Object>  getMapFromIoJsonwebtokenClaims(Claims claims){
    Map<String, Object> expectedMap = new HashMap<String, Object>();
    for(Entry<String, Object> entry : claims.entrySet()) {
        expectedMap.put(entry.getKey() , entry.getValue());
    }
    return expectedMap;
}

Upvotes: 1

Related Questions