-1

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?

tom
  • 2,137
  • 2
  • 27
  • 51

3 Answers3

6

You can use the add method of JsonObjectBuilder:

JsonObjectBuilder builder = Json.createObjectBuilder();
mapA.forEach(builder::add);
JsonObject obj = builder.build();
VGR
  • 40,506
  • 4
  • 48
  • 63
2

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);
Ryuzaki L
  • 37,302
  • 12
  • 68
  • 98
0

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();
Pd Unique
  • 26
  • 6