Reputation: 554
The question talks about a specific library but the question applies to any chain of methods that requires iteration. The Nimbus JWT+JOSE library has a class called JWTClaimsSet
which allows you to build a JWT with the following syntax:
JWTClaimsSet jwtClaims = new JWTClaimsSet.Builder()
.claim("claim1", "claim1")
.claim("claim2", "claim2")
.build()
What I'm trying to accomplish here is to programmatically add the claims. What I've tried so far is to create a class like this:
static JSONObject GenerateJWT(Map mClaims){
JWTClaimsSet jwtClaims = new JWTClaimsSet.Builder()
mClaims.each {
k,v ->
jwtClaims = jwtClaims.claims(k.toString(),v.toString())
}
jwtClaims = jwtClaims.build()
return jwtClaims.toJSONObject()
}
And call it like this:
MyClass.GenerateJWT(["claim1": "claim1", "claim2": "claim2"])
However, I get an error saying that (as indeed is the case):
Cannot cast object 'com.nimbusds.jwt.JWTClaimsSet$Builder@12f9af83' with class 'com.nimbusds.jwt.JWTClaimsSet$Builder' to class 'com.nimbusds.jwt.JWTClaimsSet'
How can iterate through the map and set each item as claim, value?
Upvotes: 2
Views: 370
Reputation: 19682
JWTClaimsSet
is a different class from JWTClaimsSet.Builder
so your static typing is throwing it off here. All of the methods on the builder return a Builder
object to allow for chaining except for build()
, which returns the final JWTClaimsSet
. I think this should work:
static JSONObject GenerateJWT(Map mClaims) {
JWTClaimsSet.Builder jwtClaimsBuilder = new JWTClaimsSet.Builder()
mClaims.each { k, v ->
jwtClaimsBuilder = jwtClaimsBuilder.claim(k.toString(), v.toString())
}
JWTClaimsSet jwtClaims = jwtClaimsBuilder.build()
return jwtClaims.toJSONObject()
}
Upvotes: 2