如何将Map转换成javax.json.JsonObject?

How to convert Map into 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
    ));

我明白了

non-static method cannot be referenced from a static context

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

这是为什么?

您可以使用 add method of JsonObjectBuilder:

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

而不是 javax.json 使用 org.json

// Create a JSON object directly from your map
JSONObject obj = new JSONObject( srcmap );
// Convert it into string
String data = obj.toString();

javax.json.JsonObjectMap<String,JsonValue> 的 child class 所以它有 putAll 方法

void putAll(Map<? extends K,? extends V> m)

因此您只需创建 JsonObject 并添加 Map

JsonObject object = Json.createObjectBuilder().build();
object.putAll(mapA);