Example usage for com.google.gson JsonObject getAsJsonPrimitive

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

Introduction

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

Prototype

public JsonPrimitive getAsJsonPrimitive(String memberName) 

Source Link

Document

Convenience method to get the specified member as a JsonPrimitive element.

Usage

From source file:org.diorite.config.serialization.JsonDeserializationData.java

License:Open Source License

@Override
public <K, T, M extends Map<K, T>> void getAsMapWithKeys(String key, Class<K> keyType, Class<T> type,
        String keyPropertyName, M map) {
    JsonElement element = this.getElement(this.element, key);
    if (element == null) {
        throw new DeserializationException(type, this, "Can't find valid value for key: " + key);
    }//w  w w . j  a  v  a2  s  . c o m
    if (element.isJsonArray()) {
        JsonArray jsonArray = element.getAsJsonArray();
        for (JsonElement jsonElement : jsonArray) {
            if (!jsonElement.isJsonObject()) {
                throw new DeserializationException(type, this,
                        "Expected json element in array list on '" + key + "' but found: " + jsonElement);
            }
            JsonObject jsonObject = jsonElement.getAsJsonObject();

            JsonElement propKeyElement = jsonObject.get(keyPropertyName);
            if (propKeyElement == null) {
                throw new DeserializationException(type, this,
                        "Missing property '" + keyPropertyName + "' in " + jsonObject + ". Key: " + key);
            }
            jsonObject.remove(keyPropertyName);

            map.put(this.context.deserialize(propKeyElement, keyType),
                    this.context.deserialize(jsonObject, type));
        }
    } else if (element.isJsonObject()) {
        JsonObject jsonObject = element.getAsJsonObject();
        for (Entry<String, JsonElement> entry : jsonObject.entrySet()) {
            JsonElement value = entry.getValue();
            if (!value.isJsonObject()) {
                throw new DeserializationException(type, this,
                        "Expected json element as values of '" + key + "' but found: " + value);
            }
            JsonObject jsonObj = value.getAsJsonObject();

            K mapKey;
            if (jsonObj.has(keyPropertyName) && jsonObj.get(keyPropertyName).isJsonPrimitive()) {
                mapKey = this.context.deserialize(jsonObj.getAsJsonPrimitive(keyPropertyName), keyType);
                jsonObj.remove(keyPropertyName);
            } else {
                mapKey = this.context.deserialize(new JsonPrimitive(entry.getKey()), keyType);
            }

            map.put(mapKey, this.context.deserialize(value, type));
        }
    } else {
        throw new DeserializationException(type, this, "Can't find valid value for key: " + key);
    }
}

From source file:org.diorite.impl.auth.properties.PropertyMapSerializer.java

License:Open Source License

@SuppressWarnings("unchecked")
@Override// w  w  w  .java  2 s. c om
public PropertyMap deserialize(final JsonElement json, final Type typeOfT,
        final JsonDeserializationContext context) throws JsonParseException {
    final PropertyMap result = new PropertyMap();

    if ((json instanceof JsonObject)) {
        final JsonObject object = (JsonObject) json;
        object.entrySet().stream().filter(entry -> (entry.getValue() instanceof JsonArray)).forEach(entry -> {
            for (final JsonElement element : (Iterable<JsonArray>) entry.getValue()) {
                result.put(entry.getKey(), new PropertyImpl(entry.getKey(), element.getAsString()));
            }
        });
    } else if ((json instanceof JsonArray)) {
        for (final JsonElement element : (Iterable<JsonArray>) json) {
            if ((element instanceof JsonObject)) {
                final JsonObject object = (JsonObject) element;
                final String name = object.getAsJsonPrimitive("name").getAsString();
                final String value = object.getAsJsonPrimitive("value").getAsString();
                if (object.has("signature")) {
                    result.put(name, new PropertyImpl(name, value,
                            object.getAsJsonPrimitive("signature").getAsString()));
                } else {
                    result.put(name, new PropertyImpl(name, value));
                }
            }
        }
    }
    return result;
}

From source file:org.eclipse.agail.polmon.rest.DiagSvc.java

License:Open Source License

private ArrayList<String> createPreferredRequirementsList(String preferredRequirements) {
    ArrayList<String> preferredRequirementsList = new ArrayList<String>();

    if (preferredRequirements != null) {
        JsonElement jsonElement = new JsonParser().parse(preferredRequirements);
        JsonArray jsonArray = jsonElement.getAsJsonArray();
        for (JsonElement currentJsonElement : jsonArray) {
            JsonObject jsonObject = currentJsonElement.getAsJsonObject();
            String attribute = translateToCligoName(jsonObject.getAsJsonPrimitive("id").getAsString());
            String value = jsonObject.getAsJsonPrimitive("value").getAsString();
            preferredRequirementsList.add(attribute + ".*" + value + ".*");
        }/*from   w  ww  .j a  va 2  s .co  m*/
    }

    return preferredRequirementsList;
}

From source file:org.eclipse.che.api.testing.server.messages.ServerTestingMessage.java

License:Open Source License

private static ServerTestingMessage internalParse(String text) {

    try {//  ww  w  . j av  a 2  s . c o m
        JsonParser parser = new JsonParser();
        JsonObject jsonObject = parser.parse(text).getAsJsonObject();

        String name = jsonObject.getAsJsonPrimitive(NAME).getAsString();
        Map<String, String> attributes = new HashMap<>();
        if (jsonObject.has(ATTRIBUTES)) {
            Set<Map.Entry<String, JsonElement>> entries = jsonObject.getAsJsonObject(ATTRIBUTES).entrySet();
            for (Map.Entry<String, JsonElement> entry : entries) {
                attributes.put(entry.getKey(), unescape(entry.getValue().getAsString()));
            }
        }

        return new ServerTestingMessage(name, attributes);
    } catch (Throwable t) {
        throw new RuntimeException(t);
    }
}

From source file:org.eclipse.ice.core.internal.Core.java

License:Open Source License

/**
 * This private operation creates an instance of the Message class from a
 * string using a JSON parser./*  w  w w.  j  a  v  a  2 s.  com*/
 *
 * This operation is synchronized so that the core can't be overloaded.
 *
 * @param messageString
 *            The original message, as a string
 * @return list list of built messages.
 */
private ArrayList<Message> buildMessagesFromString(String messageString) {

    // Create the ArrayList of messages
    ArrayList<Message> messages = new ArrayList<Message>();

    // Create the parser and gson utility
    JsonParser parser = new JsonParser();
    GsonBuilder builder = new GsonBuilder();
    Gson gson = builder.create();

    // Catch any exceptions and return the empty list
    try {

        // Make the string a json string
        JsonElement messageJson = parser.parse(messageString);
        JsonObject messageJsonObject = messageJson.getAsJsonObject();

        // Get the Item id from the json
        JsonPrimitive itemIdJson = messageJsonObject.getAsJsonPrimitive("item_id");
        int itemId = itemIdJson.getAsInt();

        // Get the array of posts from the message
        JsonArray jsonMessagesList = messageJsonObject.getAsJsonArray("posts");

        // Load the list
        for (int i = 0; i < jsonMessagesList.size(); i++) {
            // Get the message as a json element
            JsonElement jsonMessage = jsonMessagesList.get(i);
            // Marshal it into a message
            Message tmpMessage = gson.fromJson(jsonMessage, Message.class);
            // Set the item id
            if (tmpMessage != null) {
                tmpMessage.setItemId(itemId);
                // Put it in the list
                messages.add(tmpMessage);
            }
        }
    } catch (JsonParseException e) {
        // Log the message
        String err = "Core Message: " + "JSON parsing failed for message " + messageString;
        logger.error(getClass().getName() + " Exception!", e);
        logger.error(err);
    }

    return messages;
}

From source file:org.eclipse.leshan.server.demo.servlet.json.SecurityDeserializer.java

License:Open Source License

@Override
public SecurityInfo deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {

    if (json == null) {
        return null;
    }/*from  w w w  .jav a  2  s.  com*/

    SecurityInfo info = null;

    if (json.isJsonObject()) {
        JsonObject object = (JsonObject) json;

        String endpoint;
        if (object.has("endpoint")) {
            endpoint = object.get("endpoint").getAsString();
        } else {
            throw new JsonParseException("Missing endpoint");
        }

        JsonObject psk = (JsonObject) object.get("psk");
        JsonObject rpk = (JsonObject) object.get("rpk");
        JsonPrimitive x509 = object.getAsJsonPrimitive("x509");
        if (psk != null) {
            // PSK Deserialization
            String identity;
            if (psk.has("identity")) {
                identity = psk.get("identity").getAsString();
            } else {
                throw new JsonParseException("Missing PSK identity");
            }
            byte[] key;
            try {
                key = Hex.decodeHex(psk.get("key").getAsString().toCharArray());
            } catch (IllegalArgumentException e) {
                throw new JsonParseException("key parameter must be a valid hex string", e);
            }

            info = SecurityInfo.newPreSharedKeyInfo(endpoint, identity, key);
        } else if (rpk != null) {
            PublicKey key;
            try {
                byte[] x = Hex.decodeHex(rpk.get("x").getAsString().toCharArray());
                byte[] y = Hex.decodeHex(rpk.get("y").getAsString().toCharArray());
                String params = rpk.get("params").getAsString();

                AlgorithmParameters algoParameters = AlgorithmParameters.getInstance("EC");
                algoParameters.init(new ECGenParameterSpec(params));
                ECParameterSpec parameterSpec = algoParameters.getParameterSpec(ECParameterSpec.class);

                KeySpec keySpec = new ECPublicKeySpec(new ECPoint(new BigInteger(x), new BigInteger(y)),
                        parameterSpec);

                key = KeyFactory.getInstance("EC").generatePublic(keySpec);
            } catch (IllegalArgumentException | InvalidKeySpecException | NoSuchAlgorithmException
                    | InvalidParameterSpecException e) {
                throw new JsonParseException("Invalid security info content", e);
            }
            info = SecurityInfo.newRawPublicKeyInfo(endpoint, key);
        } else if (x509 != null && x509.getAsBoolean()) {
            info = SecurityInfo.newX509CertInfo(endpoint);
        } else {
            throw new JsonParseException("Invalid security info content");
        }
    }

    return info;
}

From source file:org.eclipse.recommenders.internal.coordinates.rcp.DependencyInfoJsonTypeAdapter.java

License:Open Source License

@Override
public DependencyInfo deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {
    JsonObject jsonObject = json.getAsJsonObject();

    JsonPrimitive fileElement = jsonObject.getAsJsonPrimitive("location"); //$NON-NLS-1$
    File file = new File(fileElement.getAsString());

    JsonElement typeElement = jsonObject.get("type"); //$NON-NLS-1$
    DependencyType type = context.deserialize(typeElement, DependencyType.class);

    JsonElement hintsElement = jsonObject.get("hints"); //$NON-NLS-1$
    Map<String, String> hints = context.deserialize(hintsElement, cacheType);

    return new DependencyInfo(file, type, hints);
}

From source file:org.eclipse.wst.jsdt.nodejs.ide.ui.internal.views.outdated.NpmOutdatedView.java

License:Open Source License

private String getStringValue(JsonElement jsonElement, String fieldName) {
    String value = "";
    if (jsonElement instanceof JsonObject) {
        JsonObject jsonObject = (JsonObject) jsonElement;
        JsonPrimitive jsonPrimitive = jsonObject.getAsJsonPrimitive(fieldName);
        if (jsonPrimitive != null && jsonPrimitive.isString()) {
            value = jsonPrimitive.getAsString();
        }/* w w w. j a v a 2 s  . c o  m*/
    }
    return value;
}

From source file:org.helios.dashkuj.core.apiimpl.AbstractDashku.java

License:Open Source License

/**
 * Builds a post body in post body format to send the dirty fields for the passed domain object.
 * The field values are URL encoded. /*from   ww  w .  j a  va 2  s  .  c  om*/
 * @param domainObject the domain object to generate the diff post for
 * @return the diff post body
 */
protected Buffer buildDirtyUpdatePost(AbstractDashkuDomainObject domainObject) {
    StringBuilder b = new StringBuilder();
    JsonObject jsonDomainObject = GsonFactory.getInstance().newNoSerGson().toJsonTree(domainObject)
            .getAsJsonObject();
    Set<String> fieldnames = domainObject.getDirtyFieldNames();
    if (fieldnames.isEmpty())
        return null;
    for (String dirtyFieldName : domainObject.getDirtyFieldNames()) {
        try {
            JsonPrimitive jp = jsonDomainObject.getAsJsonPrimitive(dirtyFieldName);
            String value = null;
            if (jp.isString()) {
                value = URLEncoder.encode(jp.getAsString(), "UTF-8");
            } else if (jp.isNumber()) {
                value = "" + jp.getAsNumber();
            } else if (jp.isBoolean()) {
                value = "" + jp.getAsBoolean();
            } else {
                value = jp.toString();
            }
            b.append(dirtyFieldName).append("=").append(value).append("&");
        } catch (Exception ex) {
            throw new RuntimeException("Failed to encode dirty field [" + dirtyFieldName + "]", ex);
        }
    }
    b.deleteCharAt(b.length() - 1);
    try {
        String encoded = b.toString(); //URLEncoder.encode(b.toString(), "UTF-8");
        log.info("Update Post:[\n\t{}\n]", encoded);
        return new Buffer(encoded);
    } catch (Exception e) {
        throw new RuntimeException(e); // ain't happening
    }
}

From source file:org.jeeventstore.serialization.gson.EventListTypeConverter.java

License:Open Source License

@Override
public EventList deserialize(JsonElement json, Type type, JsonDeserializationContext context)
        throws JsonParseException {

    JsonObject obj = json.getAsJsonObject();
    Integer version = obj.getAsJsonPrimitive("version").getAsInt();
    if (version != 1)
        throw new JsonParseException("Unable to parse event of version " + version);

    Iterator<JsonElement> eit = obj.getAsJsonArray("events").iterator();
    List<Serializable> eventlist = new ArrayList<>();
    while (eit.hasNext()) {
        String clazz = null;/*from ww w .  j a v  a2  s. c o m*/
        try {
            JsonObject elem = eit.next().getAsJsonObject();
            clazz = elem.getAsJsonPrimitive("type").getAsString();
            Class<? extends Serializable> eventClass = (Class<? extends Serializable>) Class.forName(clazz);
            Serializable s = context.deserialize(elem.get("body"), eventClass);
            eventlist.add(s);
        } catch (ClassNotFoundException e) {
            throw new JsonParseException("Cannot deserialize events of class " + clazz, e);
        }
    }
    return new EventList(eventlist);
}