Example usage for com.google.gson JsonPrimitive getAsString

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

Introduction

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

Prototype

@Override
public String getAsString() 

Source Link

Document

convenience method to get this element as a String.

Usage

From source file:org.opendolphin.core.comm.JsonCodec.java

License:Apache License

private Object toValidValue(JsonElement jsonElement) {
    if (jsonElement.isJsonNull()) {
        return null;
    } else if (jsonElement.isJsonPrimitive()) {
        JsonPrimitive primitive = jsonElement.getAsJsonPrimitive();
        if (primitive.isBoolean()) {
            return primitive.getAsBoolean();
        } else if (primitive.isString()) {
            return primitive.getAsString();
        } else {//from  w w w . j  ava 2  s  .  co m
            return primitive.getAsNumber();
        }
    } else if (jsonElement.isJsonObject()) {
        JsonObject jsonObject = jsonElement.getAsJsonObject();
        if (jsonObject.has(Date.class.toString())) {
            try {
                return new SimpleDateFormat(ISO8601_FORMAT)
                        .parse(jsonObject.getAsJsonPrimitive(Date.class.toString()).getAsString());
            } catch (Exception e) {
                throw new RuntimeException("Can not converte!", e);
            }
        } else if (jsonObject.has(BigDecimal.class.toString())) {
            try {
                return new BigDecimal(jsonObject.getAsJsonPrimitive(BigDecimal.class.toString()).getAsString());
            } catch (Exception e) {
                throw new RuntimeException("Can not converte!", e);
            }
        } else if (jsonObject.has(Float.class.toString())) {
            try {
                return Float.valueOf(jsonObject.getAsJsonPrimitive(Float.class.toString()).getAsString());
            } catch (Exception e) {
                throw new RuntimeException("Can not converte!", e);
            }
        } else if (jsonObject.has(Double.class.toString())) {
            try {
                return Double.valueOf(jsonObject.getAsJsonPrimitive(Double.class.toString()).getAsString());
            } catch (Exception e) {
                throw new RuntimeException("Can not converte!", e);
            }
        }
    }
    throw new RuntimeException("Can not converte!");
}

From source file:org.openecomp.sdc.be.model.tosca.converters.ToscaValueBaseConverter.java

License:Open Source License

public Object json2JavaPrimitive(JsonPrimitive prim) {
    if (prim.isBoolean()) {
        return prim.getAsBoolean();
    } else if (prim.isString()) {
        return prim.getAsString();
    } else if (prim.isNumber()) {
        String strRepesentation = prim.getAsString();
        if (strRepesentation.contains(".")) {
            return prim.getAsDouble();
        } else {/*from w  ww  .j ava2s.com*/
            return prim.getAsInt();
        }
    } else {
        throw new IllegalStateException();
    }
}

From source file:org.openhab.io.neeo.internal.NeeoUtil.java

License:Open Source License

/**
 * Converts a JSON property to a string//  www . j a  v a 2  s .  c o m
 *
 * @param jo           the non-null {@link JsonObject} to use
 * @param propertyName the non-empty property name
 * @return the possibly null string representation
 */
@Nullable
public static String getString(JsonObject jo, String propertyName) {
    Objects.requireNonNull(jo, "jo cannot be null");
    requireNotEmpty(propertyName, "propertyName cannot be empty");

    final JsonPrimitive jp = jo.getAsJsonPrimitive(propertyName);
    return jp == null || jp.isJsonNull() ? null : jp.getAsString();
}

From source file:org.openqa.selenium.json.JsonToBeanConverter.java

License:Apache License

@SuppressWarnings("unchecked")
private <T> T convert(Class<T> clazz, Object source, int depth) {
    if (source == null || source instanceof JsonNull) {
        return null;
    }/*from   w w w  . j  a va2  s.c  o  m*/

    if (source instanceof JsonElement) {
        JsonElement json = (JsonElement) source;

        if (json.isJsonPrimitive()) {
            JsonPrimitive jp = json.getAsJsonPrimitive();

            if (String.class.equals(clazz)) {
                return (T) jp.getAsString();
            }

            if (jp.isNumber()) {
                if (Integer.class.isAssignableFrom(clazz) || int.class.equals(clazz)) {
                    return (T) Integer.valueOf(jp.getAsNumber().intValue());
                } else if (Long.class.isAssignableFrom(clazz) || long.class.equals(clazz)) {
                    return (T) Long.valueOf(jp.getAsNumber().longValue());
                } else if (Float.class.isAssignableFrom(clazz) || float.class.equals(clazz)) {
                    return (T) Float.valueOf(jp.getAsNumber().floatValue());
                } else if (Double.class.isAssignableFrom(clazz) || double.class.equals(clazz)) {
                    return (T) Double.valueOf(jp.getAsNumber().doubleValue());
                } else {
                    return (T) convertJsonPrimitive(jp);
                }
            }
        }
    }

    if (isPrimitive(source.getClass())) {
        return (T) source;
    }

    if (isEnum(clazz, source)) {
        return (T) convertEnum(clazz, source);
    }

    if ("".equals(String.valueOf(source))) {
        return (T) source;
    }

    if (Command.class.equals(clazz)) {
        JsonObject json = new JsonParser().parse((String) source).getAsJsonObject();

        SessionId sessionId = null;
        if (json.has("sessionId") && !json.get("sessionId").isJsonNull()) {
            sessionId = convert(SessionId.class, json.get("sessionId"), depth + 1);
        }

        String name = json.get("name").getAsString();
        if (json.has("parameters")) {
            Map<String, ?> args = (Map<String, ?>) convert(HashMap.class, json.get("parameters"), depth + 1);
            return (T) new Command(sessionId, name, args);
        }

        return (T) new Command(sessionId, name);
    }

    if (Response.class.equals(clazz)) {
        Response response = new Response();
        JsonObject json = source instanceof JsonObject ? (JsonObject) source
                : new JsonParser().parse((String) source).getAsJsonObject();

        if (json.has("error") && !json.get("error").isJsonNull()) {
            String state = json.get("error").getAsString();
            response.setState(state);
            response.setStatus(errorCodes.toStatus(state, Optional.empty()));
            response.setValue(convert(Object.class, json.get("message")));
        }
        if (json.has("state") && !json.get("state").isJsonNull()) {
            String state = json.get("state").getAsString();
            response.setState(state);
            response.setStatus(errorCodes.toStatus(state, Optional.empty()));
        }
        if (json.has("status") && !json.get("status").isJsonNull()) {
            JsonElement status = json.get("status");
            if (status.getAsJsonPrimitive().isString()) {
                String state = status.getAsString();
                response.setState(state);
                response.setStatus(errorCodes.toStatus(state, Optional.empty()));
            } else {
                int intStatus = status.getAsInt();
                response.setState(errorCodes.toState(intStatus));
                response.setStatus(intStatus);
            }
        }
        if (json.has("sessionId") && !json.get("sessionId").isJsonNull()) {
            response.setSessionId(json.get("sessionId").getAsString());
        }

        if (json.has("value")) {
            response.setValue(convert(Object.class, json.get("value")));
        } else {
            response.setValue(convert(Object.class, json));
        }

        return (T) response;
    }

    if (SessionId.class.equals(clazz)) {
        // Stupid heuristic to tell if we are dealing with a selenium 2 or 3 session id.
        JsonElement json = source instanceof String ? new JsonParser().parse((String) source).getAsJsonObject()
                : (JsonElement) source;
        if (json.isJsonPrimitive()) {
            return (T) new SessionId(json.getAsString());
        }
        return (T) new SessionId(json.getAsJsonObject().get("value").getAsString());
    }

    if (Capabilities.class.isAssignableFrom(clazz)) {
        JsonObject json = source instanceof JsonElement ? ((JsonElement) source).getAsJsonObject()
                : new JsonParser().parse(source.toString()).getAsJsonObject();
        Map<String, Object> map = convertMap(json.getAsJsonObject(), depth);
        return (T) new MutableCapabilities(map);
    }

    if (Date.class.equals(clazz)) {
        return (T) new Date(Long.valueOf(String.valueOf(source)));
    }

    if (source instanceof String && !((String) source).startsWith("{") && Object.class.equals(clazz)) {
        return (T) source;
    }

    Method fromJson = getMethod(clazz, "fromJson");
    if (fromJson != null) {
        try {
            return (T) fromJson.invoke(null, source.toString());
        } catch (ReflectiveOperationException e) {
            throw new WebDriverException(e);
        }
    }

    if (depth == 0) {
        if (source instanceof String) {
            source = new JsonParser().parse((String) source);
        }
    }

    if (source instanceof JsonElement) {
        JsonElement element = (JsonElement) source;

        if (element.isJsonNull()) {
            return null;
        }

        if (element.isJsonPrimitive()) {
            return (T) convertJsonPrimitive(element.getAsJsonPrimitive());
        }

        if (element.isJsonArray()) {
            return (T) convertList(element.getAsJsonArray(), depth);
        }

        if (element.isJsonObject()) {
            if (Map.class.isAssignableFrom(clazz)) {
                return (T) convertMap(element.getAsJsonObject(), depth);
            }

            if (Object.class.equals(clazz)) {
                return (T) convertMap(element.getAsJsonObject(), depth);
            }

            return convertBean(clazz, element.getAsJsonObject(), depth);
        }
    }

    return (T) source; // Crap shoot here; probably a string.
}

From source file:org.openqa.selenium.json.JsonToBeanConverter.java

License:Apache License

private Object convertJsonPrimitive(JsonPrimitive json) {
    if (json.isBoolean()) {
        return json.getAsBoolean();
    } else if (json.isNumber()) {
        if (json.getAsLong() == json.getAsDouble()) {
            return json.getAsLong();
        }/*w  w  w  .j  a  v  a  2s  . c  o m*/
        return json.getAsDouble();
    } else if (json.isString()) {
        return json.getAsString();
    } else {
        return null;
    }
}

From source file:org.openqa.selenium.remote.JsonToBeanConverter.java

License:Apache License

@SuppressWarnings("unchecked")
private <T> T convert(Class<T> clazz, Object source, int depth) {
    if (source == null || source instanceof JsonNull) {
        return null;
    }/*from   w  ww. j  a v  a 2s .co  m*/

    if (source instanceof JsonElement) {
        JsonElement json = (JsonElement) source;

        if (json.isJsonPrimitive()) {
            JsonPrimitive jp = json.getAsJsonPrimitive();

            if (String.class.equals(clazz)) {
                return (T) jp.getAsString();
            }

            if (jp.isNumber()) {
                if (Integer.class.isAssignableFrom(clazz) || int.class.equals(clazz)) {
                    return (T) Integer.valueOf(jp.getAsNumber().intValue());
                } else if (Long.class.isAssignableFrom(clazz) || long.class.equals(clazz)) {
                    return (T) Long.valueOf(jp.getAsNumber().longValue());
                } else if (Float.class.isAssignableFrom(clazz) || float.class.equals(clazz)) {
                    return (T) Float.valueOf(jp.getAsNumber().floatValue());
                } else if (Double.class.isAssignableFrom(clazz) || double.class.equals(clazz)) {
                    return (T) Double.valueOf(jp.getAsNumber().doubleValue());
                } else {
                    return (T) convertJsonPrimitive(jp);
                }
            }
        }
    }

    if (isPrimitive(source.getClass())) {
        return (T) source;
    }

    if (isEnum(clazz, source)) {
        return (T) convertEnum(clazz, source);
    }

    if ("".equals(String.valueOf(source))) {
        return (T) source;
    }

    if (Command.class.equals(clazz)) {
        JsonObject json = new JsonParser().parse((String) source).getAsJsonObject();

        SessionId sessionId = null;
        if (json.has("sessionId") && !json.get("sessionId").isJsonNull()) {
            sessionId = convert(SessionId.class, json.get("sessionId"), depth + 1);
        }

        String name = json.get("name").getAsString();
        if (json.has("parameters")) {
            Map<String, ?> args = (Map<String, ?>) convert(HashMap.class, json.get("parameters"), depth + 1);
            return (T) new Command(sessionId, name, args);
        }

        return (T) new Command(sessionId, name);
    }

    if (Response.class.equals(clazz)) {
        Response response = new Response();
        JsonObject json = source instanceof JsonObject ? (JsonObject) source
                : new JsonParser().parse((String) source).getAsJsonObject();

        if (json.has("error") && !json.get("error").isJsonNull()) {
            String state = json.get("error").getAsString();
            response.setState(state);
            response.setStatus(errorCodes.toStatus(state, Optional.empty()));
            response.setValue(convert(Object.class, json.get("message")));
        }
        if (json.has("state") && !json.get("state").isJsonNull()) {
            String state = json.get("state").getAsString();
            response.setState(state);
            response.setStatus(errorCodes.toStatus(state, Optional.empty()));
        }
        if (json.has("status") && !json.get("status").isJsonNull()) {
            JsonElement status = json.get("status");
            if (status.getAsJsonPrimitive().isString()) {
                String state = status.getAsString();
                response.setState(state);
                response.setStatus(errorCodes.toStatus(state, Optional.empty()));
            } else {
                int intStatus = status.getAsInt();
                response.setState(errorCodes.toState(intStatus));
                response.setStatus(intStatus);
            }
        }
        if (json.has("sessionId") && !json.get("sessionId").isJsonNull()) {
            response.setSessionId(json.get("sessionId").getAsString());
        }

        if (json.has("value")) {
            response.setValue(convert(Object.class, json.get("value")));
        } else {
            response.setValue(convert(Object.class, json));
        }

        return (T) response;
    }

    if (SessionId.class.equals(clazz)) {
        // Stupid heuristic to tell if we are dealing with a selenium 2 or 3 session id.
        JsonElement json = source instanceof String ? new JsonParser().parse((String) source).getAsJsonObject()
                : (JsonElement) source;
        if (json.isJsonPrimitive()) {
            return (T) new SessionId(json.getAsString());
        }
        return (T) new SessionId(json.getAsJsonObject().get("value").getAsString());
    }

    if (Capabilities.class.isAssignableFrom(clazz)) {
        JsonObject json = source instanceof JsonElement ? ((JsonElement) source).getAsJsonObject()
                : new JsonParser().parse(source.toString()).getAsJsonObject();
        Map<String, Object> map = convertMap(json.getAsJsonObject(), depth);
        return (T) new DesiredCapabilities(map);
    }

    if (Date.class.equals(clazz)) {
        return (T) new Date(Long.valueOf(String.valueOf(source)));
    }

    if (source instanceof String && !((String) source).startsWith("{") && Object.class.equals(clazz)) {
        return (T) source;
    }

    Method fromJson = getMethod(clazz, "fromJson");
    if (fromJson != null) {
        try {
            return (T) fromJson.invoke(null, source.toString());
        } catch (IllegalArgumentException e) {
            throw new WebDriverException(e);
        } catch (IllegalAccessException e) {
            throw new WebDriverException(e);
        } catch (InvocationTargetException e) {
            throw new WebDriverException(e);
        }
    }

    if (depth == 0) {
        if (source instanceof String) {
            source = new JsonParser().parse((String) source);
        }
    }

    if (source instanceof JsonElement) {
        JsonElement element = (JsonElement) source;

        if (element.isJsonNull()) {
            return null;
        }

        if (element.isJsonPrimitive()) {
            return (T) convertJsonPrimitive(element.getAsJsonPrimitive());
        }

        if (element.isJsonArray()) {
            return (T) convertList(element.getAsJsonArray(), depth);
        }

        if (element.isJsonObject()) {
            if (Map.class.isAssignableFrom(clazz)) {
                return (T) convertMap(element.getAsJsonObject(), depth);
            }

            if (Object.class.equals(clazz)) {
                return (T) convertMap(element.getAsJsonObject(), depth);
            }

            return convertBean(clazz, element.getAsJsonObject(), depth);
        }
    }

    return (T) source; // Crap shoot here; probably a string.
}

From source file:org.owasp.dependencycheck.data.artifactory.ArtifactorySearch.java

License:Apache License

/**
 * Process the Artifactory response.//from   w w w. j a  va2s  . c o m
 *
 * @param dependency the dependency
 * @param conn the HTTP URL Connection
 * @return a list of the Maven Artifact information
 * @throws IOException thrown if there is an I/O error
 */
protected List<MavenArtifact> processResponse(Dependency dependency, HttpURLConnection conn)
        throws IOException {
    final JsonObject asJsonObject;
    try (final InputStreamReader streamReader = new InputStreamReader(conn.getInputStream(),
            StandardCharsets.UTF_8)) {
        asJsonObject = new JsonParser().parse(streamReader).getAsJsonObject();
    }
    final JsonArray results = asJsonObject.getAsJsonArray("results");
    final int numFound = results.size();
    if (numFound == 0) {
        throw new FileNotFoundException("Artifact " + dependency + " not found in Artifactory");
    }

    final List<MavenArtifact> result = new ArrayList<>(numFound);
    for (JsonElement jsonElement : results) {

        final JsonObject checksumList = jsonElement.getAsJsonObject().getAsJsonObject("checksums");
        final JsonPrimitive sha256Primitive = checksumList.getAsJsonPrimitive("sha256");
        final String sha1 = checksumList.getAsJsonPrimitive("sha1").getAsString();
        final String sha256 = sha256Primitive == null ? null : sha256Primitive.getAsString();
        final String md5 = checksumList.getAsJsonPrimitive("md5").getAsString();

        checkHashes(dependency, sha1, sha256, md5);

        final String downloadUri = jsonElement.getAsJsonObject().getAsJsonPrimitive("downloadUri")
                .getAsString();

        final String path = jsonElement.getAsJsonObject().getAsJsonPrimitive("path").getAsString();

        final Matcher pathMatcher = PATH_PATTERN.matcher(path);
        if (!pathMatcher.matches()) {
            throw new IllegalStateException(
                    "Cannot extract the Maven information from the apth retrieved in Artifactory " + path);
        }
        final String groupId = pathMatcher.group("groupId").replace('/', '.');
        final String artifactId = pathMatcher.group("artifactId");
        final String version = pathMatcher.group("version");

        result.add(new MavenArtifact(groupId, artifactId, version, downloadUri,
                MavenArtifact.derivePomUrl(artifactId, version, downloadUri)));
    }

    return result;
}

From source file:org.plos.crepo.model.metadata.RepoMetadata.java

License:Open Source License

@VisibleForTesting
static Object convertJsonToImmutable(JsonElement element) {
    if (element.isJsonNull()) {
        return null;
    }/* w ww .  j  a v a2s.co  m*/
    if (element.isJsonPrimitive()) {
        JsonPrimitive primitive = element.getAsJsonPrimitive();
        if (primitive.isString())
            return primitive.getAsString();
        if (primitive.isNumber())
            return asNumber(primitive);
        if (primitive.isBoolean())
            return primitive.getAsBoolean();
        throw new RuntimeException("JsonPrimitive is not one of the expected primitive types");
    }
    if (element.isJsonArray()) {
        JsonArray array = element.getAsJsonArray();
        if (array.size() == 0)
            return Collections.emptyList();
        List<Object> convertedList = new ArrayList<>(array.size());
        for (JsonElement arrayElement : array) {
            Object convertedElement = convertJsonToImmutable(arrayElement);
            convertedList.add(convertedElement);
        }
        return Collections.unmodifiableList(convertedList);
    }
    if (element.isJsonObject()) {
        Set<Map.Entry<String, JsonElement>> entries = element.getAsJsonObject().entrySet();
        if (entries.size() == 0)
            return Collections.emptyMap();
        Map<String, Object> convertedMap = Maps.newHashMapWithExpectedSize(entries.size());
        for (Map.Entry<String, JsonElement> entry : entries) {
            String key = Preconditions.checkNotNull(entry.getKey());
            Object value = convertJsonToImmutable(entry.getValue());
            convertedMap.put(key, value);
        }
        return Collections.unmodifiableMap(convertedMap);
    }
    throw new RuntimeException("JsonElement is not one of the expected subtypes");
}

From source file:org.qcert.camp.translator.Rule2CAMP.java

License:Open Source License

/**
 * Obtain the correct kind of value from a JsonPrimitive node.  The kinds we support are int, String, and boolean
 * @param primitive the JsonPrimitive node
 * @return the value/*from   w  ww . ja va2  s  .  com*/
 */
private static Object valueFromJson(JsonPrimitive primitive) {
    if (primitive.isString())
        return primitive.getAsString();
    if (primitive.isNumber())
        return primitive.getAsInt();
    if (primitive.isBoolean())
        return primitive.getAsBoolean();
    throw new IllegalStateException();
}

From source file:org.qcert.runtime.UnaryOperators.java

License:Apache License

private static void tostring(StringBuilder sb, JsonPrimitive jp) {
    if (jp.isString()) {
        sb.append(jp.getAsString());
    } else {/*  w  ww .  j  ava 2  s .  co  m*/
        sb.append(jp.toString());
    }
}