遍历Map以在Groovy中构建点符号链接方法 [英] Iterate through Map to build dot notation chained methods in Groovy

查看:135
本文介绍了遍历Map以在Groovy中构建点符号链接方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

该问题涉及特定的库,但该问题适用于需要迭代的任何方法链. Nimbus JWT + JOSE库具有一个名为JWTClaimsSet的类,该类使您可以使用以下语法来构建JWT:

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()

}

并这样称呼它:

MyClass.GenerateJWT(["claim1": "claim1", "claim2": "claim2"])

但是,我得到这样的错误提示(确实如此):

However, I get an error saying that (as indeed is the case):

无法将类为'com.nimbusds.jwt.JWTClaimsSet $ Builder'的对象'com.nimbusds.jwt.JWTClaimsSet$Builder@12f9af83'转换为类'com.nimbusds.jwt.JWTClaimsSet'

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?

推荐答案

JWTClaimsSet是与JWTClaimsSet.Builder不同的类,因此您的静态类型将其扔掉.生成器上的所有方法都返回一个Builder对象,以允许为build()链接 except ,该对象返回最终的JWTClaimsSet.我认为这应该可行:

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()
}

这篇关于遍历Map以在Groovy中构建点符号链接方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆