首页 > 解决方案 > 如何将 Map 转换为 javax.json.JsonObject?

问题描述

我可以这样做:

Map<String, String> mapA = ...;
Map<String, String> mapB = mapA.entrySet().stream()
    .collect(Collectors.toMap(
        Map.Entry::getKey,
        Map.Entry::getValue
    ));

但是当我试图这样做时:

... mapA.entrySet().stream()
    .collect(JsonCollectors.toJsonObject(
        JsonObject.Entry::getKey,
        JsonObject.Entry::getValue
    ));

我明白了

不能从静态上下文中引用非静态方法

对于JsonObject.Entry::getKey, JsonObject.Entry::getValue部分。

为什么?

标签: javalambdajavax.json

解决方案


您可以使用JsonObjectBuilder 的 add 方法

JsonObjectBuilder builder = Json.createObjectBuilder();
mapA.forEach(builder::add);
JsonObject obj = builder.build();

推荐阅读