简体   繁体   English

在 Kotlin 中转换为 JsonObject

[英]Casting to JsonObject in Kotlin

I have the following Java code:我有以下 Java 代码:

var jwks = ((List<Object>) keys.getList()).stream()
                            .map(o -> new JsonObject((Map<String, Object>) o))
                            .collect(Collectors.toList());

and would like to translate safely into Kotlin code.并希望安全地转换为 Kotlin 代码。

When I copy the code into Intellj, then it translates for me as follows:当我将代码复制到 Intellj 中时,它为我翻译如下:

val jwks = (keys.list as List<Any?>).stream()
        .map { o: Any? -> JsonObject(o as Map<String?, Any?>?) }
        .collect(Collectors.toList())

Can I do it better or should I let it as is.我可以做得更好还是应该保持原样。

Update更新

Maybe I have to provide more context.也许我必须提供更多背景信息。 What I am trying to do is, to implement JWT Authorization for Vert.x with Keycloak in Kotlin regarding to the tutorial https://vertx.io/blog/jwt-authorization-for-vert-x-with-keycloak/ .我想做的是,根据教程https://vertx.io/blog/jwt-authorization-for-vert-x-with-keycloak/在 Kotlin 中使用 Keycloak 实现 Vert.x 的 JWT 授权。 I am trying to rewrite the method我正在尝试重写该方法

private Future<Startup> setupJwtAuth(Startup startup) {

    var jwtConfig = startup.config.getJsonObject("jwt");
    var issuer = jwtConfig.getString("issuer");
    var issuerUri = URI.create(issuer);

    // derive JWKS uri from Keycloak issuer URI
    var jwksUri = URI.create(jwtConfig.getString("jwksUri", String.format("%s://%s:%d%s",
            issuerUri.getScheme(), issuerUri.getHost(), issuerUri.getPort(), issuerUri.getPath() + "/protocol/openid-connect/certs")));

    var promise = Promise.<JWTAuth>promise();

    // fetch JWKS from `/certs` endpoint
    webClient.get(jwksUri.getPort(), jwksUri.getHost(), jwksUri.getPath())
            .as(BodyCodec.jsonObject())
            .send(ar -> {

                if (!ar.succeeded()) {
                    startup.bootstrap.fail(String.format("Could not fetch JWKS from URI: %s", jwksUri));
                    return;
                }

                var response = ar.result();

                var jwksResponse = response.body();
                var keys = jwksResponse.getJsonArray("keys");

                // Configure JWT validation options
                var jwtOptions = new JWTOptions();
                jwtOptions.setIssuer(issuer);

                // extract JWKS from keys array
                var jwks = ((List<Object>) keys.getList()).stream()
                        .map(o -> new JsonObject((Map<String, Object>) o))
                        .collect(Collectors.toList());

                // configure JWTAuth
                var jwtAuthOptions = new JWTAuthOptions();
                jwtAuthOptions.setJwks(jwks);
                jwtAuthOptions.setJWTOptions(jwtOptions);
                jwtAuthOptions.setPermissionsClaimKey(jwtConfig.getString("permissionClaimsKey", "realm_access/roles"));

                JWTAuth jwtAuth = JWTAuth.create(vertx, jwtAuthOptions);
                promise.complete(jwtAuth);
            });

    return promise.future().compose(auth -> {
        jwtAuth = auth;
        return Future.succeededFuture(startup);
    });
}

into Kotlin language.进入 Kotlin 语言。

You can use Kotlin's star projection which basically handles unknown generics in a type-safe way.您可以使用 Kotlin 的星形投影,它基本上以类型安全的方式处理未知的泛型。

(keys.list as List<Map<*, *>>).map { JsonObject(it) }

Since there is no multi-mapping there is no need of Stream/Sequence API.由于没有多重映射,因此不需要 Stream/Sequence API。

However, if you want to use lazy-evaluation (each element going through all mapping then next element in same way rather than mapping all element then running next map):但是,如果您想使用延迟评估(每个元素都以相同的方式通过所有映射然后下一个元素,而不是映射所有元素然后运行下一个映射):

(keys.list as List<Map<*, *>>)
        .asSequence()
        .map { JsonObject(it) }
        .map { /* Maybe some other mapping */ }
        .filter { /* Maybe some filter */ }
        .take(5)  // Or some other intermediate operation
        .toList()  // Finally start the operations and collect

Edit: I forgot that the keys are String , so you can cast to List<Map<String, *>> instead :)编辑:我忘了键是String ,所以你可以转换为List<Map<String, *>> :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM