Example usage for com.google.gson JsonElement isJsonPrimitive

List of usage examples for com.google.gson JsonElement isJsonPrimitive

Introduction

In this page you can find the example usage for com.google.gson JsonElement isJsonPrimitive.

Prototype

public boolean isJsonPrimitive() 

Source Link

Document

provides check for verifying if this element is a primitive or not.

Usage

From source file:org.apache.tika.eval.tokens.AnalyzerDeserializer.java

License:Apache License

private static Map<String, String> mapify(JsonElement paramsEl) {
    if (paramsEl == null || paramsEl.isJsonNull()) {
        return Collections.EMPTY_MAP;
    }/*w  ww .  jav  a  2s.  c o m*/
    if (!paramsEl.isJsonObject()) {
        throw new IllegalArgumentException("Expecting map, not: " + paramsEl.toString());
    }
    Map<String, String> params = new HashMap<>();
    for (Map.Entry<String, JsonElement> e : ((JsonObject) paramsEl).entrySet()) {
        JsonElement value = e.getValue();
        if (!value.isJsonPrimitive()) {
            throw new IllegalArgumentException(
                    "Expecting parameter to have primitive value: " + value.toString());
        }
        String v = e.getValue().getAsString();
        params.put(e.getKey(), v);
    }
    return params;
}

From source file:org.apache.tika.metadata.serialization.JsonMetadataDeserializer.java

License:Apache License

/**
 * Deserializes a json object (equivalent to: Map<String, String[]>) 
 * into a Metadata object.//from w  w  w  .  j ava  2 s.  c o  m
 * 
 * @param element to serialize
 * @param type (ignored)
 * @param context (ignored)
 * @return Metadata 
 * @throws JsonParseException if element is not able to be parsed
 */
@Override
public Metadata deserialize(JsonElement element, Type type, JsonDeserializationContext context)
        throws JsonParseException {

    final JsonObject obj = element.getAsJsonObject();
    Metadata m = new Metadata();
    for (Map.Entry<String, JsonElement> entry : obj.entrySet()) {
        String key = entry.getKey();
        JsonElement v = entry.getValue();
        if (v.isJsonPrimitive()) {
            m.set(key, v.getAsString());
        } else if (v.isJsonArray()) {
            JsonArray vArr = v.getAsJsonArray();
            Iterator<JsonElement> itr = vArr.iterator();
            while (itr.hasNext()) {
                JsonElement valueItem = itr.next();
                m.add(key, valueItem.getAsString());
            }

        }
    }
    return m;
}

From source file:org.apache.twill.internal.json.JsonUtils.java

License:Apache License

/**
 * Returns a String representation of the given property.
 *///from   w w w .j ava  2s  . c om
public static String getAsString(JsonObject json, String property) {
    JsonElement jsonElement = json.get(property);
    if (jsonElement == null || jsonElement.isJsonNull()) {
        return null;
    }
    if (jsonElement.isJsonPrimitive()) {
        return jsonElement.getAsString();
    }
    return jsonElement.toString();
}

From source file:org.bimserver.database.actions.DownloadByJsonQueryDatabaseAction.java

License:Open Source License

private void processInclude(JsonObject query, JsonObject queryPart, IfcModelInterface model,
        QueryInterface queryInterface, List<IdEObject> objects)
        throws BimserverDatabaseException, IfcModelInterfaceException {
    if (queryPart.get("include").isJsonArray()) {
        JsonArray includes = queryPart.get("include").getAsJsonArray();
        for (JsonElement include : includes) {
            if (include.isJsonPrimitive()) {
                processSingleInclude(query, include, model, queryInterface, objects);
            } else if (include.isJsonObject()) {
                processDefine(query, (JsonObject) include, model, queryInterface, objects);
            }//w w  w.j av  a2  s . c  o  m
        }
    } else if (queryPart.get("include").isJsonObject()) {
        processDefine(query, queryPart.get("include").getAsJsonObject(), model, queryInterface, objects);
    }
}

From source file:org.bimserver.database.actions.DownloadByJsonQueryDatabaseAction.java

License:Open Source License

private void processSingleInclude(JsonObject query, JsonElement include, IfcModelInterface model,
        QueryInterface queryInterface, List<IdEObject> objects)
        throws BimserverDatabaseException, IfcModelInterfaceException {
    if (include.isJsonPrimitive()) {
        String includeName = include.getAsString();
        if (query.has("defines")) {
            JsonObject defines = query.get("defines").getAsJsonObject();
            if (defines.has(includeName)) {
                JsonObject define = defines.get(includeName).getAsJsonObject();
                processDefine(query, define, model, queryInterface, objects);
            } else {
                throw new BimserverDatabaseException("No define with name '" + includeName + "' found");
            }//from w  w w .  j av  a2  s.c  o m
        } else {
            throw new BimserverDatabaseException("No define with name '" + includeName + "' found");
        }
    }
}

From source file:org.blockartistry.DynSurround.client.footsteps.parsers.AcousticsJsonReader.java

License:MIT License

private IAcoustic solveAcoustic(final JsonElement unsolved) throws JsonParseException {
    IAcoustic ret = null;//from   w ww.j ava 2  s.c  o m

    if (unsolved.isJsonObject()) {
        ret = solveAcousticsCompound(unsolved.getAsJsonObject());
    } else if (unsolved.isJsonPrimitive() && unsolved.getAsJsonPrimitive().isString()) { // Is a sound name
        final BasicAcoustic a = new BasicAcoustic();
        prepareDefaults(a);
        setupSoundName(a, unsolved.getAsString());
        ret = a;
    }

    if (ret == null)
        throw new JsonParseException("Unresolved Json element: \r\n" + unsolved.toString());
    return ret;
}

From source file:org.cinchapi.concourse.util.Convert.java

License:Open Source License

/**
 * Convert a JSON formatted string to a mapping that associates each key
 * with the Java objects that represent the corresponding values. This
 * method is designed to parse simple JSON structures that associate keys to
 * simple values or arrays without knowing the type of each element ahead of
 * time./*ww w  . j  a v a2 s .  c  om*/
 * <p>
 * This method can properly handle JSON strings that abide by the following
 * rules:
 * <ul>
 * <li>The top level element in the JSON string must be an Object</li>
 * <li>No nested objects (e.g. a key cannot map to an object)</li>
 * <li>No null values</li>
 * </ul>
 * </p>
 * 
 * @param json
 * @return the converted data
 */
public static Multimap<String, Object> jsonToJava(String json) {
    // NOTE: in this method we use the #toString instead of the #getAsString
    // method of each JsonElement to trigger the conversion to a java
    // primitive to ensure that quotes are taken into account and we
    // properly convert strings masquerading as numbers (e.g. "3").
    Multimap<String, Object> data = LinkedHashMultimap.create();
    JsonParser parser = new JsonParser();
    JsonElement top = parser.parse(json);
    if (!top.isJsonObject()) {
        throw new JsonParseException("The JSON string must encapsulate data within an object");
    }
    JsonObject object = (JsonObject) parser.parse(json);
    for (Entry<String, JsonElement> entry : object.entrySet()) {
        String key = entry.getKey();
        JsonElement val = entry.getValue();
        if (val.isJsonArray()) {
            // If we have an array, add the elements individually. If there
            // are any duplicates in the array, they will be filtered out by
            // virtue of the fact that a LinkedHashMultimap does not store
            // dupes.
            Iterator<JsonElement> it = val.getAsJsonArray().iterator();
            while (it.hasNext()) {
                JsonElement elt = it.next();
                if (elt.isJsonPrimitive()) {
                    Object value = jsonElementToJava(elt);
                    data.put(key, value);
                } else {
                    throw new JsonParseException(
                            "Cannot parse a non-primitive " + "element inside of an array");
                }
            }
        } else {
            Object value = jsonElementToJava(val);
            data.put(key, value);
        }
    }
    return data;
}

From source file:org.couchbase.mock.subdoc.Executor.java

License:Apache License

private void ensureUnique(JsonArray array) throws SubdocException {
    if (!value.isJsonPrimitive() && !value.isJsonNull()) {
        throw new CannotInsertException("Cannot verify uniqueness with non-primitives");
    }// ww  w  .j  a  va2  s. c om

    String valueString = value.toString();
    for (int i = 0; i < array.size(); i++) {
        JsonElement e = array.get(i);
        if (!e.isJsonPrimitive()) {
            throw new PathMismatchException("Values in the array are not all primitives");
        }
        if (e.toString().equals(valueString)) {
            throw new PathExistsException();
        }
    }
}

From source file:org.couchbase.mock.subdoc.Path.java

License:Apache License

public void validateComponentType(int ix, JsonElement parent) throws PathMismatchException {
    Component comp = components.get(ix);
    if (parent.isJsonPrimitive() || parent.isJsonNull()) {
        throw new PathMismatchException();
    }/*from   ww w .j  av  a2s .  c  o  m*/

    if (comp.isIndex()) {
        if (!parent.isJsonArray()) {
            throw new PathMismatchException();
        }
    } else {
        if (!parent.isJsonObject()) {
            throw new PathMismatchException();
        }
    }
}

From source file:org.cvasilak.jboss.mobile.admin.net.TalkToJBossServerTask.java

License:Open Source License

@Override
protected void onPostExecute(JsonElement reply) {
    super.onPostExecute(reply);

    isTaskFinished = true;/*from ww  w . ja  va  2s  . c  om*/

    if (callback == null)
        return;

    if (!reply.isJsonObject())
        callback.onFailure(new RuntimeException("Invalid Response from server!"));

    JsonObject jsonObj = (JsonObject) reply;

    if (!jsonObj.has("outcome"))
        callback.onFailure(new RuntimeException("Invalid Response from server!"));
    else {
        String outcome = jsonObj.get("outcome").getAsString();

        if (outcome.equals("success")) {
            callback.onSuccess(jsonObj.get("result"));
        } else {
            JsonElement elem = jsonObj.get("failure-description");

            if (elem.isJsonPrimitive()) {
                callback.onFailure(new RuntimeException(elem.getAsString()));
            } else if (elem.isJsonObject())
                callback.onFailure(new RuntimeException(
                        elem.getAsJsonObject().get("domain-failure-description").toString()));
        }
    }

}