Search code examples
javalambdajavax.json

How to convert Map into javax.json.JsonObject?


I can do so:

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

But when I'm trying to do this:

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

I get

non-static method cannot be referenced from a static context

for the JsonObject.Entry::getKey, JsonObject.Entry::getValue part.

Why's that?


Solution

  • You can use the add method of JsonObjectBuilder:

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