Example usage for javax.json JsonObject getJsonObject

List of usage examples for javax.json JsonObject getJsonObject

Introduction

In this page you can find the example usage for javax.json JsonObject getJsonObject.

Prototype

JsonObject getJsonObject(String name);

Source Link

Document

Returns the object value to which the specified name is mapped.

Usage

From source file:Main.java

public static void main(String[] args) {
    String personJSONData = "  {" + "   \"name\": \"Jack\", " + "   \"age\" : 13, "
            + "   \"isMarried\" : false, " + "   \"address\": { " + "     \"street\": \"#1234, Main Street\", "
            + "     \"zipCode\": \"123456\" " + "   }, "
            + "   \"phoneNumbers\": [\"011-111-1111\", \"11-111-1111\"] " + " }";

    JsonReader reader = Json.createReader(new StringReader(personJSONData));

    JsonObject personObject = reader.readObject();

    reader.close();/*from   w w  w. java 2 s  .  c  o  m*/

    System.out.println("Name   : " + personObject.getString("name"));
    System.out.println("Age    : " + personObject.getInt("age"));
    System.out.println("Married: " + personObject.getBoolean("isMarried"));

    JsonObject addressObject = personObject.getJsonObject("address");
    System.out.println("Address: ");
    System.out.println(addressObject.getString("street"));
    System.out.println(addressObject.getString("zipCode"));

    System.out.println("Phone  : ");
    JsonArray phoneNumbersArray = personObject.getJsonArray("phoneNumbers");
    for (JsonValue jsonValue : phoneNumbersArray) {
        System.out.println(jsonValue.toString());
    }
}

From source file:org.json.StackExchangeAPI.java

private static void parseStackExchange(String jsonStr) {
    JsonReader reader = null;/*  w  w  w.  j a  v  a2 s  .  c om*/
    try {
        reader = Json.createReader(new StringReader(jsonStr));
        JsonObject jsonObject = reader.readObject();
        reader.close();
        JsonArray array = jsonObject.getJsonArray("items");
        for (JsonObject result : array.getValuesAs(JsonObject.class)) {

            JsonObject ownerObject = result.getJsonObject("owner");
            // int ownerReputation = ownerObject.getInt("reputation");
            //  System.out.println("Reputation:"+ownerReputation);
            int viewCount = result.getInt("view_count");
            System.out.println("View Count :" + viewCount);
            int answerCount = result.getInt("answer_count");
            System.out.println("Answer Count :" + answerCount);
            String link = result.getString("link");
            System.out.println("URL: " + link);
            String title = result.getString("title");
            System.out.println("Title: " + title);
            String body = result.getString("body");
            System.out.println("Body: " + body);
            JsonArray tagsArray = result.getJsonArray("tags");
            StringBuilder tagBuilder = new StringBuilder();
            int i = 1;
            for (JsonValue tag : tagsArray) {
                tagBuilder.append(tag.toString());
                if (i < tagsArray.size())
                    tagBuilder.append(",");
                i++;
            }

            System.out.println("Tags: " + tagBuilder.toString());
            System.out.println("------------------------------------------");
        }

    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

From source file:io.hakbot.util.JsonUtil.java

/**
 * Returns a json object that is a child of the specified parent object with the specified name. If parent
 * is null or the specified name cannot be found, method will return null.
 *//*from ww  w . j  a  v a2  s  .c o  m*/
public static JsonObject getJsonChildObject(JsonObject parent, String name) {
    return (parent != null && parent.containsKey(name)) ? parent.getJsonObject(name) : null;
}

From source file:com.lyonsdensoftware.config.DeviceConfigUtils.java

/**
 * Reads the {@link DeviceConfig} from disk. Pass in the name of the config file
 *
 * @return The configuration./*  www .  jav  a2s .com*/
 */
public static DeviceConfig readConfigFile(String filename) {
    FileInputStream file = null;
    try {
        deviceConfigName = filename.trim();
        file = new FileInputStream(deviceConfigName);
        JsonReader json = Json.createReader(file);
        JsonObject configObject = json.readObject();

        JsonObject wundergroundObject = configObject.getJsonObject("wundergroundApi");
        String wundergroundApiKey = wundergroundObject.getString("wundergroundApiKey");
        String wundergroundStateIdentifier = wundergroundObject.getString("wundergroundStateIdentifier");
        String wundergroundCity = wundergroundObject.getString("wundergroundCity");

        String productId = configObject.getString("productId");
        String dsn = configObject.getString("dsn");

        JsonObject pythonTCPSettings = configObject.getJsonObject("pythonTCPSettings");
        String hostname = pythonTCPSettings.getString("hostname");
        int port = pythonTCPSettings.getInt("port");

        DeviceConfig deviceConfig = new DeviceConfig(wundergroundApiKey, wundergroundStateIdentifier,
                wundergroundCity, productId, dsn, hostname, port);

        return deviceConfig;
    } catch (FileNotFoundException e) {
        throw new RuntimeException("The required file " + deviceConfigName + " could not be opened.", e);
    } finally {
        IOUtils.closeQuietly(file);
    }
}

From source file:com.amazon.alexa.avs.config.DeviceConfigUtils.java

/**
 * Reads the {@link DeviceConfig} from disk. Pass in the name of the config file
 *
 * @return The configuration.//from w ww  . ja v  a  2s.c o m
 */
public static DeviceConfig readConfigFile(String filename) {
    FileInputStream file = null;
    try {
        deviceConfigName = filename.trim();
        file = new FileInputStream(deviceConfigName);
        JsonReader json = Json.createReader(file);
        JsonObject configObject = json.readObject();

        JsonObject companionServiceObject = configObject.getJsonObject(DeviceConfig.COMPANION_SERVICE);
        CompanionServiceInformation companionServiceInfo = null;
        if (companionServiceObject != null) {
            String serviceUrl = companionServiceObject
                    .getString(DeviceConfig.CompanionServiceInformation.SERVICE_URL, null);
            String sessionId = companionServiceObject
                    .getString(DeviceConfig.CompanionServiceInformation.SESSION_ID, null);
            String sslClientKeyStore = companionServiceObject
                    .getString(DeviceConfig.CompanionServiceInformation.SSL_CLIENT_KEYSTORE, null);
            String sslClientKeyStorePassphrase = companionServiceObject
                    .getString(DeviceConfig.CompanionServiceInformation.SSL_CLIENT_KEYSTORE_PASSPHRASE, null);
            String sslCaCert = companionServiceObject
                    .getString(DeviceConfig.CompanionServiceInformation.SSL_CA_CERT, null);

            companionServiceInfo = new CompanionServiceInformation(serviceUrl, sslClientKeyStore,
                    sslClientKeyStorePassphrase, sslCaCert);
            companionServiceInfo.setSessionId(sessionId);
        }

        JsonObject companionAppObject = configObject.getJsonObject(DeviceConfig.COMPANION_APP);
        CompanionAppInformation companionAppInfo = null;
        if (companionAppObject != null) {
            int localPort = companionAppObject.getInt(DeviceConfig.CompanionAppInformation.LOCAL_PORT, -1);
            String lwaUrl = companionAppObject.getString(DeviceConfig.CompanionAppInformation.LWA_URL, null);
            String clientId = companionAppObject.getString(DeviceConfig.CompanionAppInformation.CLIENT_ID,
                    null);
            String refreshToken = companionAppObject
                    .getString(DeviceConfig.CompanionAppInformation.REFRESH_TOKEN, null);
            String sslKeyStore = companionAppObject.getString(DeviceConfig.CompanionAppInformation.SSL_KEYSTORE,
                    null);
            String sslKeyStorePassphrase = companionAppObject
                    .getString(DeviceConfig.CompanionAppInformation.SSL_KEYSTORE_PASSPHRASE, null);

            companionAppInfo = new CompanionAppInformation(localPort, lwaUrl, sslKeyStore,
                    sslKeyStorePassphrase);
            companionAppInfo.setClientId(clientId);
            companionAppInfo.setRefreshToken(refreshToken);
        }

        String productId = configObject.getString(DeviceConfig.PRODUCT_ID, null);
        String dsn = configObject.getString(DeviceConfig.DSN, null);
        String provisioningMethod = configObject.getString(DeviceConfig.PROVISIONING_METHOD, null);
        String avsHost = configObject.getString(DeviceConfig.AVS_HOST, null);
        boolean wakeWordAgentEnabled = configObject.getBoolean(DeviceConfig.WAKE_WORD_AGENT_ENABLED, false);
        String locale = configObject.getString(DeviceConfig.LOCALE, null);

        DeviceConfig deviceConfig = new DeviceConfig(productId, dsn, provisioningMethod, wakeWordAgentEnabled,
                locale, companionAppInfo, companionServiceInfo, avsHost);

        return deviceConfig;
    } catch (FileNotFoundException e) {
        throw new RuntimeException("The required file " + deviceConfigName + " could not be opened.", e);
    } finally {
        IOUtils.closeQuietly(file);
    }
}

From source file:org.apache.tamaya.etcd.EtcdAccessor.java

private static void parsePrevNode(String key, Map<String, String> result, JsonObject o) {
    if (o.containsKey("prevNode")) {
        final JsonObject prevNode = o.getJsonObject("prevNode");
        if (prevNode.containsKey("createdIndex")) {
            result.put("_" + key + ".prevNode.createdIndex", String.valueOf(prevNode.getInt("createdIndex")));
        }/* w w w  .j a v a 2  s  .c o  m*/
        if (prevNode.containsKey("modifiedIndex")) {
            result.put("_" + key + ".prevNode.modifiedIndex", String.valueOf(prevNode.getInt("modifiedIndex")));
        }
        if (prevNode.containsKey("expiration")) {
            result.put("_" + key + ".prevNode.expiration", String.valueOf(prevNode.getString("expiration")));
        }
        if (prevNode.containsKey("ttl")) {
            result.put("_" + key + ".prevNode.ttl", String.valueOf(prevNode.getInt("ttl")));
        }
        result.put("_" + key + ".prevNode.value", prevNode.getString("value"));
    }
}

From source file:org.jboss.as.test.integration.logging.formatters.JsonFormatterTestCase.java

private static void validateStackTrace(final JsonObject json) {
    checkNonNull(json, "refId");
    checkNonNull(json, "exceptionType");
    checkNonNull(json, "message");
    checkNonNull(json, "frames");
    if (json.get("causedBy") != null) {
        validateStackTrace(json.getJsonObject("causedBy").getJsonObject("exception"));
    }/*from w ww.  j ava 2s .co m*/
}

From source file:org.jboss.as.test.integration.logging.formatters.JsonFormatterTestCase.java

private static void validateStackTrace(final JsonObject json, final boolean validateFormatted,
        final boolean validateStructured) {
    if (validateFormatted) {
        Assert.assertNotNull(json.get("stackTrace"));
    } else {//w ww.j  a v  a2s  . c o  m
        Assert.assertNull(json.get("stackTrace"));
    }
    if (validateStructured) {
        validateStackTrace(json.getJsonObject("exception"));
    } else {
        Assert.assertNull(json.get("exception"));
    }
}

From source file:edu.cornell.mannlib.vitro.webapp.controller.datatools.dumprestore.JsonToNquads.java

private void processRecord() throws IOException {
    String text = buffer.toString("UTF-8");
    log.debug("Parsing record: '" + text + "'");
    try (JsonReader jsRead = Json.createReader(new StringReader(text))) {
        JsonObject jsRecord = jsRead.readObject();
        DumpNode s = DumpNode.fromJson(jsRecord.getJsonObject("s"));
        DumpNode p = DumpNode.fromJson(jsRecord.getJsonObject("p"));
        DumpNode o = DumpNode.fromJson(jsRecord.getJsonObject("o"));
        DumpNode g = DumpNode.fromJson(jsRecord.getJsonObject("g"));

        if (g == null) {
            writer.write(String.format("%s %s %s .\n", s.toNquad(), p.toNquad(), o.toNquad()));
        } else {// ww w.j  a v a  2 s. c  o  m
            writer.write(String.format("%s %s %s %s .\n", s.toNquad(), p.toNquad(), o.toNquad(), g.toNquad()));
        }

        recordCount++;
        if (recordCount % 10000 == 0) {
            log.info("dumped " + recordCount + " records.");
        }
    } catch (Exception e) {
        log.error("Failed to parse record: '" + text + "'", e);
        throw new RuntimeException(e);
    }
}

From source file:co.runrightfast.vertx.orientdb.ODatabaseDocumentTxHealthCheck.java

private boolean isHealthy(final JsonObject healthcheckData) {
    if (documentObjects.isEmpty()) {
        return true;
    }/*  w w  w  .  j a va2  s  . c o  m*/

    final JsonObject counts = healthcheckData.getJsonObject("counts");
    return !documentObjects.stream()
            .filter(clazz -> counts.getInt(DocumentObject.documentClassName(clazz)) == -1).findFirst()
            .isPresent();
}