How to convert Map into javax.json.JsonObject?

3.7k Views Asked by At

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?

3

There are 3 best solutions below

1
VGR On BEST ANSWER

You can use the add method of JsonObjectBuilder:

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

Instead of javax.json use org.json

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

javax.json.JsonObject is child class of Map<String,JsonValue> so it has putAll method

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

So you can just create JsonObject and add the Map

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