Java EE 8: converting java.util.Properties or Map into JsonObject

Java EE 8 / JSON-P 1.1 come with a convenience JsonCollector, which simplifies the conversion of Properties and Maps into an JsonObject


import java.util.Properties;
import static java.util.stream.Collectors.toMap;
import javax.json.Json;
import static javax.json.Json.createValue;
import javax.json.JsonObject;
import javax.json.JsonValue;
import javax.json.stream.JsonCollectors;

//...
        
@GET
@Path("/system-properties")
public JsonObject systemProperties() {

    Properties properties = System.getProperties();
    Map<String, JsonValue> map = properties.entrySet().
            stream().
            collect(toMap(k -> k.toString(), v -> createValue(v.getValue().toString())));
    return map.entrySet().stream().collect(JsonCollectors.toJsonObject());
}    

@GET
@Path("/environment-variables")
public JsonObject environmentVariables() {
    Map<String, JsonValue> environment
            = System.getenv().
                    entrySet().
                    stream().
                    collect(toMap(Map.Entry::getKey, v -> createValue(v.getValue())));
    return environment.entrySet().stream().collect(JsonCollectors.toJsonObject());
}


The code is taken from: https://github.com/AdamBien/ping

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


Web Apps, SPA, PWA with vanilla Java Script (ES 6+), CSS 3 and WebStandards only. As simple as possible, but not simpler. See you at: (Progressive) Web apps, Single Page Apps and WebStandards airhacks workshops at MUC airport, Winter Edition

airhacks.fm the podcast:

Stay in touch: airhacks.news.

Comments:

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