Converting a Map Into javax.json.JsonObject with Java 8

With a custom Collector:


import java.util.Map;
import java.util.stream.Collector;
import javax.json.Json;
import javax.json.JsonObject;
import javax.json.JsonObjectBuilder;


public interface JsonCollectors {

    public static <T> Collector<Map.Entry<T, T>, ?, JsonObjectBuilder> toJsonBuilder() {
        return Collector.of(Json::createObjectBuilder, (t, u) -> {
            t.add(String.valueOf(String.valueOf(u.getKey())), String.valueOf(u.getValue()));
        }, JsonCollectors::merge);
    }

    static JsonObjectBuilder merge(JsonObjectBuilder left, JsonObjectBuilder right) {
        JsonObjectBuilder retVal = Json.createObjectBuilder();
        JsonObject leftObject = left.build();
        JsonObject rightObject = right.build();
        leftObject.keySet().stream().forEach((key) -> retVal.add(key, leftObject.get(key)));
        rightObject.keySet().stream().forEach((key) -> retVal.add(key, rightObject.get(key)));
        return retVal;
    }
}


...a Map<String, String> can be easily converted into a JsonObject:

    public JsonObject environmentVariables() {
        Map<String, String> environment = System.getenv();
        return environment.entrySet().
        stream().
        collect(JsonCollectors.toJsonBuilder()).
		build();
    }

The sample above is taken from github.com/AdamBien/ping

See you at Java EE Workshops at Munich Airport, Terminal 2 or Virtual Dedicated Workshops / consulting. Is Munich's airport too far? Learn from home: airhacks.io.


NEW online workshop: WebStandards Igniter (online)

Airport MUC workshops: Java EE 8, Java 9: Bootstrap, Effective, Architectures, Single Page Apps, Progressive Web Apps, HTML 5, ES 6, CSS 3 and Microservices

Podcast: airhacks.fm and newsletter: airhacks.news

A book about rethinking Java EE Patterns

Comments:

In case of a rest service to get JSON one can simply use:

@GET
@Produces(MediaType.APPLICATION_JSON)
public Map<String, String> environmentVariables() {
Map<String, String> environment = System.getenv();
return environment;
}

Posted by Michael on June 12, 2016 at 09:07 AM CEST #

Post a Comment:
  • HTML Syntax: NOT allowed
realworldpatterns.com
Online Workshops
...the last 150 posts
...the last 10 comments
License