Example usage for com.google.gson JsonObject getAsString

List of usage examples for com.google.gson JsonObject getAsString

Introduction

In this page you can find the example usage for com.google.gson JsonObject getAsString.

Prototype

public String getAsString() 

Source Link

Document

convenience method to get this element as a string value.

Usage

From source file:org.openhab.binding.tradfri.internal.discovery.TradfriDiscoveryService.java

License:Open Source License

@Override
public void onUpdate(String instanceId, JsonObject data) {
    ThingUID bridge = handler.getThing().getUID();
    try {/*from   w ww.  ja  va2 s  .  c om*/
        if (data.has(INSTANCE_ID)) {
            int id = data.get(INSTANCE_ID).getAsInt();
            String type = data.get(TYPE).getAsString();
            JsonObject deviceInfo = data.get(DEVICE).getAsJsonObject();
            String model = deviceInfo.get(DEVICE_MODEL).getAsString();
            ThingUID thingId = null;

            if (TYPE_LIGHT.equals(type) && data.has(LIGHT)) {
                JsonObject state = data.get(LIGHT).getAsJsonArray().get(0).getAsJsonObject();

                // Color temperature light:
                // We do not always receive a COLOR attribute, even the light supports it - but the gateway does not
                // seem to have this information, if the bulb is unreachable. We therefore also check against
                // concrete model names.
                // Color light:
                // As the protocol does not distinguishes between color and full-color lights,
                // we check if the "CWS" identifier is given in the model name
                ThingTypeUID thingType = null;
                if (model != null && model.contains(COLOR_MODELS_IDENTIFIER)) {
                    thingType = THING_TYPE_COLOR_LIGHT;
                }
                if (thingType == null && //
                        (state.has(COLOR)
                                || (model != null && Arrays.asList(COLOR_TEMP_MODELS).contains(model)))) {
                    thingType = THING_TYPE_COLOR_TEMP_LIGHT;
                }
                if (thingType == null) {
                    thingType = THING_TYPE_DIMMABLE_LIGHT;
                }
                thingId = new ThingUID(thingType, bridge, Integer.toString(id));
            } else if (TYPE_PLUG.equals(type) && data.has(PLUG)) {
                // Smart plug
                ThingTypeUID thingType = THING_TYPE_ONOFF_PLUG;
                thingId = new ThingUID(thingType, bridge, Integer.toString(id));
            } else if (TYPE_SWITCH.equals(type) && data.has(SWITCH)) {
                // Remote control and wireless dimmer
                // As protocol does not distinguishes between remote control and wireless dimmer,
                // we check for the whole model name
                ThingTypeUID thingType = (model != null && REMOTE_CONTROLLER_MODEL.equals(model))
                        ? THING_TYPE_REMOTE_CONTROL
                        : THING_TYPE_DIMMER;
                thingId = new ThingUID(thingType, bridge, Integer.toString(id));
            } else if (TYPE_SENSOR.equals(type) && data.has(SENSOR)) {
                // Motion sensor
                thingId = new ThingUID(THING_TYPE_MOTION_SENSOR, bridge, Integer.toString(id));
            }

            if (thingId == null) {
                // we didn't identify any device, so let's quit
                logger.debug(
                        "Ignoring unknown device on TRADFRI gateway:\n\ttype : {}\n\tmodel: {}\n\tinfo : {}",
                        type, model, deviceInfo.getAsString());
                return;
            }

            String label = data.get(NAME).getAsString();

            Map<String, Object> properties = new HashMap<>(1);
            properties.put("id", id);
            properties.put(PROPERTY_MODEL_ID, model);

            if (deviceInfo.get(DEVICE_VENDOR) != null) {
                properties.put(PROPERTY_VENDOR, deviceInfo.get(DEVICE_VENDOR).getAsString());
            }
            if (deviceInfo.get(DEVICE_FIRMWARE) != null) {
                properties.put(PROPERTY_FIRMWARE_VERSION, deviceInfo.get(DEVICE_FIRMWARE).getAsString());
            }

            logger.debug("Adding device {} to inbox", thingId);
            DiscoveryResult discoveryResult = DiscoveryResultBuilder.create(thingId).withBridge(bridge)
                    .withLabel(label).withProperties(properties).withRepresentationProperty("id").build();
            thingDiscovered(discoveryResult);
        }
    } catch (JsonSyntaxException e) {
        logger.debug("JSON error during discovery: {}", e.getMessage());
    }
}

From source file:org.royaldev.royalcommands.shaded.mkremins.fanciful.FancyMessage.java

License:Mozilla Public License

/**
 * Deserializes a fancy message from its JSON representation. This JSON representation is of the format of
 * that returned by {@link #toJSONString()}, and is compatible with vanilla inputs.
 *
 * @param json The JSON string which represents a fancy message.
 * @return A {@code FancyMessage} representing the parameterized JSON message.
 *//*from w  w  w.  j ava  2  s  . c o m*/
public static FancyMessage deserialize(String json) {
    JsonObject serialized = _stringParser.parse(json).getAsJsonObject();
    JsonArray extra = serialized.getAsJsonArray("extra"); // Get the extra component
    FancyMessage returnVal = new FancyMessage();
    returnVal.messageParts.clear();
    for (JsonElement mPrt : extra) {
        MessagePart component = new MessagePart();
        JsonObject messagePart = mPrt.getAsJsonObject();
        for (Map.Entry<String, JsonElement> entry : messagePart.entrySet()) {
            // Deserialize text
            if (TextualComponent.isTextKey(entry.getKey())) {
                // The map mimics the YAML serialization, which has a "key" field and one or more "value" fields
                Map<String, Object> serializedMapForm = new HashMap<String, Object>(); // Must be object due to Bukkit serializer API compliance
                serializedMapForm.put("key", entry.getKey());
                if (entry.getValue().isJsonPrimitive()) {
                    // Assume string
                    serializedMapForm.put("value", entry.getValue().getAsString());
                } else {
                    // Composite object, but we assume each element is a string
                    for (Map.Entry<String, JsonElement> compositeNestedElement : entry.getValue()
                            .getAsJsonObject().entrySet()) {
                        serializedMapForm.put("value." + compositeNestedElement.getKey(),
                                compositeNestedElement.getValue().getAsString());
                    }
                }
                component.text = TextualComponent.deserialize(serializedMapForm);
            } else if (MessagePart.stylesToNames.inverse().containsKey(entry.getKey())) {
                if (entry.getValue().getAsBoolean()) {
                    component.styles.add(MessagePart.stylesToNames.inverse().get(entry.getKey()));
                }
            } else if ("color".equals(entry.getKey())) {
                component.color = ChatColor.valueOf(entry.getValue().getAsString().toUpperCase());
            } else if ("clickEvent".equals(entry.getKey())) {
                JsonObject object = entry.getValue().getAsJsonObject();
                component.clickActionName = object.get("action").getAsString();
                component.clickActionData = object.get("value").getAsString();
            } else if ("hoverEvent".equals(entry.getKey())) {
                JsonObject object = entry.getValue().getAsJsonObject();
                component.hoverActionName = object.get("action").getAsString();
                if (object.get("value").isJsonPrimitive()) {
                    // Assume string
                    component.hoverActionData = new JsonString(object.get("value").getAsString());
                } else {
                    // Assume composite type
                    // The only composite type we currently store is another FancyMessage
                    // Therefore, recursion time!
                    component.hoverActionData = deserialize(object.get("value")
                            .toString() /* This should properly serialize the JSON object as a JSON string */);
                }
            } else if ("insertion".equals(entry.getKey())) {
                component.insertionData = entry.getValue().getAsString();
            } else if ("with".equals(entry.getKey())) {
                for (JsonElement object : entry.getValue().getAsJsonArray()) {
                    if (object.isJsonPrimitive()) {
                        component.translationReplacements.add(new JsonString(object.getAsString()));
                    } else {
                        // Only composite type stored in this array is - again - FancyMessages
                        // Recurse within this function to parse this as a translation replacement
                        component.translationReplacements.add(deserialize(object.toString()));
                    }
                }
            }
        }
        returnVal.messageParts.add(component);
    }
    return returnVal;
}

From source file:ua.pp.msk.cliqr.validators.JobValidator.java

License:Apache License

private boolean validateNVJson(JsonElement je) throws ParameterException {
    if (!je.isJsonObject()) {
        throw new WrongParameterException("This json element " + je.getAsString()
                + "\nshould look like a json object with 'name' and 'value' String parameters");
    } else {/*from ww  w  .  j a  v a  2s  .c o  m*/
        JsonObject jo = je.getAsJsonObject();
        if (!jo.has(NAME)) {
            throw new WrongParameterException(
                    "This object:" + jo.getAsString() + " should contain a name property");
        } else {
            if (!jo.get(NAME).isJsonPrimitive()) {
                throw new WrongParameterException(
                        "This: " + jo.get(NAME).getAsString() + " should be a json primitive");
            }
        }
        if (!jo.has(VALUE)) {
            throw new WrongParameterException(
                    "This object:" + jo.getAsString() + " should contain a value property");
        } else {
            if (!jo.get(VALUE).isJsonPrimitive()) {
                throw new WrongParameterException(
                        "This: " + jo.get(VALUE).getAsString() + " should be a json primitive");
            }
        }
    }
    return true;
}

From source file:ua.pp.msk.cliqr.validators.JobValidator.java

License:Apache License

private boolean validateJob(JsonElement je) throws ParameterException {
    if (je.isJsonObject()) {
        JsonObject jo = je.getAsJsonObject();
        if (!jo.has(SERVICETIERID)) {
            throw new MissingParameterException("Missing service tier id element");
        } else {//from w  w w  . ja  va 2  s .c  o  m
            if (jo.get(SERVICETIERID).isJsonNull() || jo.get(SERVICETIERID).getAsString().isEmpty()) {
                throw new MissingParameterException("Service tier id element is empty or null value");
            }
        }

        if (!jo.has(PARAMETERS)) {
            throw new MissingParameterException("Missing parameters element in job " + jo.getAsString());
        } else {
            if (jo.get(PARAMETERS).isJsonNull()) {
                throw new MissingParameterException("Parameters element is empty or null value");
            }
            if (jo.has(CLOUDPARAMETERS)) {
                validateCloudParams(jo.get(CLOUDPARAMETERS));
            } else {
                throw new MissingParameterException(
                        "Parameters element must contain here " + CLOUDPARAMETERS + " property");
            }
            if (jo.has(APPLICATIONPARAMENTERS)) {
                validateAppParams(jo.get(APPLICATIONPARAMENTERS));
            }
        }
    } else {
        throw new WrongParameterException("Job must be a JsonObject");
    }

    return true;
}