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.

Comments:

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