Example usage for com.google.gson JsonElement getAsInt

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

Introduction

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

Prototype

public int getAsInt() 

Source Link

Document

convenience method to get this element as a primitive integer value.

Usage

From source file:com.simiacryptus.mindseye.layers.java.TensorConcatLayer.java

License:Apache License

/**
 * Instantiates a new Img eval key.//from  ww w.  j  a va  2 s.  c  o m
 *
 * @param json the json
 */
protected TensorConcatLayer(@Nonnull final JsonObject json) {
    super(json);
    JsonElement maxBands = json.get("maxBands");
    if (null != maxBands)
        setMaxBands(maxBands.getAsInt());
}

From source file:com.sixt.service.framework.protobuf.ProtobufUtil.java

License:Apache License

private static Object parseField(Descriptors.FieldDescriptor field, JsonElement value,
        Message.Builder enclosingBuilder) throws Exception {
    switch (field.getType()) {
    case DOUBLE://  w w w.j  av a 2  s.  c  o m
        if (!value.isJsonPrimitive()) {
            // fail;
        }
        return value.getAsDouble();
    case FLOAT:
        if (!value.isJsonPrimitive()) {
            // fail;
        }
        return value.getAsFloat();
    case INT64:
    case UINT64:
    case FIXED64:
    case SINT64:
    case SFIXED64:
        if (!value.isJsonPrimitive()) {
            // fail
        }
        return value.getAsLong();
    case INT32:
    case UINT32:
    case FIXED32:
    case SINT32:
    case SFIXED32:
        if (!value.isJsonPrimitive()) {
            // fail
        }
        return value.getAsInt();
    case BOOL:
        if (!value.isJsonPrimitive()) {
            // fail
        }
        return value.getAsBoolean();
    case STRING:
        if (!value.isJsonPrimitive()) {
            // fail
        }
        return value.getAsString();
    case GROUP:
    case MESSAGE:
        if (!value.isJsonObject()) {
            // fail
        }
        return fromJson(enclosingBuilder.newBuilderForField(field), value.getAsJsonObject());
    case BYTES:
        if (!value.isJsonPrimitive()) {
            // fail
        }
        return ByteString.copyFrom(BaseEncoding.base64().decode(value.getAsString()));
    case ENUM:
        if (!value.isJsonPrimitive()) {
            // fail
        }
        String protoEnumValue = CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, value.getAsString());
        return field.getEnumType().findValueByName(protoEnumValue);
    }
    return null;
}

From source file:com.skysql.manager.api.ChartProperties.java

License:Open Source License

public ChartProperties deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {

    ChartProperties chartProperties = new ChartProperties();

    JsonElement jsonElement = json.getAsJsonObject().get("chartProperties");
    if (jsonElement != null && !jsonElement.isJsonNull()) {

        LinkedHashMap<String, ArrayList<ChartMappings>> chartsMap = new LinkedHashMap<String, ArrayList<ChartMappings>>();
        chartProperties.setChartsMap(chartsMap);

        JsonArray array = jsonElement.getAsJsonArray();
        for (int i = 0; i < array.size(); i++) {
            JsonObject jsonObject = array.get(i).getAsJsonObject();

            String systemType = (jsonElement = jsonObject.get("systemtype")).isJsonNull() ? null
                    : jsonElement.getAsString();
            JsonArray mappingJson = jsonObject.get("mappings").getAsJsonArray();
            int length = mappingJson.size();

            ArrayList<ChartMappings> chartsList = new ArrayList<ChartMappings>(length);

            for (int j = 0; j < length; j++) {
                JsonObject mappingObject = mappingJson.get(j).getAsJsonObject();

                JsonElement element;
                String name = (element = mappingObject.get("name")).isJsonNull() ? null : element.getAsString();
                String description = (element = mappingObject.get("description")).isJsonNull() ? null
                        : element.getAsString();
                String unit = (element = mappingObject.get("unit")).isJsonNull() ? null : element.getAsString();
                String type = (element = mappingObject.get("type")).isJsonNull() ? null : element.getAsString();
                int points = (element = mappingObject.get("points")).isJsonNull() ? null : element.getAsInt();
                element = mappingObject.get("monitorIDs");
                ArrayList<String> monitorIDs = new ArrayList<String>();
                if (element != null && !element.isJsonNull()) {
                    JsonArray IDs = element.getAsJsonArray();
                    for (int k = 0; k < IDs.size(); k++) {
                        String id = String.valueOf(IDs.get(k).getAsString());
                        monitorIDs.add(id);
                    }/*from  w  ww  .  ja  v  a 2s  . c  o m*/
                }
                ChartMappings chartMapping = new ChartMappings(name, description, unit, type, points,
                        monitorIDs);
                chartsList.add(chartMapping);
            }

            chartsMap.put(systemType, chartsList);
        }

    }

    jsonElement = json.getAsJsonObject().get("chartSettings");
    if (jsonElement != null && !jsonElement.isJsonNull()) {
        JsonObject settingsJson = jsonElement.getAsJsonObject();
        JsonElement element;
        chartProperties.timeSpan = (element = settingsJson.get("timeSpan")).isJsonNull() ? 0
                : element.getAsInt();
        chartProperties.theme = (element = settingsJson.get("theme")).isJsonNull() ? null
                : element.getAsString();
    }

    return chartProperties;

}

From source file:com.skysql.manager.api.WriteResponse.java

License:Open Source License

public WriteResponse deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {

    WriteResponse writeResponse = new WriteResponse();

    JsonElement jsonElement = json.getAsJsonObject().get("deletecount");
    if (jsonElement != null && !jsonElement.isJsonNull()) {
        writeResponse.setDeleteCount(jsonElement.getAsInt());
    }//ww  w  .j  av a  2  s. c  o m

    jsonElement = json.getAsJsonObject().get("updatecount");
    if (jsonElement != null && !jsonElement.isJsonNull()) {
        writeResponse.setUpdateCount(jsonElement.getAsInt());
    }

    jsonElement = json.getAsJsonObject().get("insertkey");
    if (jsonElement != null && !jsonElement.isJsonNull()) {
        writeResponse.setInsertKey(jsonElement.getAsString());
    }

    return writeResponse;
}

From source file:com.sldeditor.exportdata.esri.symbols.BaseSymbol.java

License:Open Source License

/**
 * Gets the value as an integer./* w  ww .ja  va2  s .  c o  m*/
 *
 * @param obj the obj
 * @param field the field
 * @return the double
 */
protected static int getInt(JsonObject obj, String field) {
    int value = 0;

    if (obj != null) {
        JsonElement element = obj.get(field);

        if (element != null) {
            value = element.getAsInt();
        }
    }
    return value;
}

From source file:com.solidfire.jsvcgen.serialization.OptionalAdapter.java

License:Open Source License

/**
 * Deserializes an Optional object./*from ww  w. j  av  a2s .com*/
 *
 * @param json    the element to deserialize.
 * @param typeOfT type of the expected return value.
 * @param context Context used for deserialization.
 * @return An Optional object containing an object of type typeOfT.
 */
public Optional<?> deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) {
    if (!json.isJsonObject() && !json.isJsonArray()) {
        if (json.isJsonNull() || json.getAsString() == null) {
            return Optional.empty();
        }
    }

    ParameterizedType pType = (ParameterizedType) typeOfT;
    Type genericType = pType.getActualTypeArguments()[0];

    // Special handling for string, "" will return Optional.of("")
    if (genericType.equals(String.class)) {
        return Optional.of(json.getAsString());
    }

    if (!json.isJsonObject() && !json.isJsonArray() && json.getAsString().trim().length() == 0) {
        return Optional.empty();
    }

    if (json.isJsonObject() || json.isJsonArray()) {
        if (json.isJsonNull()) {
            return Optional.empty();
        }
    }

    if (genericType.equals(Integer.class)) {
        return Optional.of(json.getAsInt());
    } else if (genericType.equals(Long.class)) {
        return Optional.of(json.getAsLong());
    } else if (genericType.equals(Double.class)) {
        return Optional.of(json.getAsDouble());
    }

    // Defer deserialization to handler for type contained in Optional
    Object obj = context.deserialize(json, genericType);
    OptionalAdaptorUtils.initializeAllNullOptionalFieldsAsEmpty(obj);
    return Optional.of(obj);
}

From source file:com.stackmob.sdk.request.StackMobAccessTokenRequest.java

License:Apache License

private static StackMobRawCallback getIntermediaryCallback(final StackMobSession session,
        final StackMobRawCallback callback) {
    return new StackMobRawCallback() {
        @Override//from w ww  . java  2s  .  co m
        public void unsent(StackMobException e) {
            callback.unsent(e);
        }

        @Override
        public void temporaryPasswordResetRequired(StackMobException e) {
            callback.temporaryPasswordResetRequired(e);
        }

        @Override
        public void done(HttpVerb requestVerb, String requestURL,
                List<Map.Entry<String, String>> requestHeaders, String requestBody, Integer responseStatusCode,
                List<Map.Entry<String, String>> responseHeaders, byte[] responseBody) {
            JsonElement responseElt = new JsonParser().parse(new String(responseBody));
            byte[] finalResponseBody = responseBody;
            if (responseElt.isJsonObject()) {
                // Parse out the token and expiration
                JsonElement tokenElt = responseElt.getAsJsonObject().get("access_token");
                JsonElement macKeyElt = responseElt.getAsJsonObject().get("mac_key");
                JsonElement expirationElt = responseElt.getAsJsonObject().get("expires_in");
                JsonElement refreshTokenElt = responseElt.getAsJsonObject().get("refresh_token");
                if (tokenElt != null && tokenElt.isJsonPrimitive() && tokenElt.getAsJsonPrimitive().isString()
                        && macKeyElt != null && macKeyElt.isJsonPrimitive()
                        && macKeyElt.getAsJsonPrimitive().isString() && expirationElt != null
                        && expirationElt.isJsonPrimitive() && expirationElt.getAsJsonPrimitive().isNumber()
                        && refreshTokenElt != null && refreshTokenElt.isJsonPrimitive()
                        && refreshTokenElt.getAsJsonPrimitive().isString()) {
                    session.setOAuth2TokensAndExpiration(tokenElt.getAsString(), macKeyElt.getAsString(),
                            refreshTokenElt.getAsString(), expirationElt.getAsInt());

                }
                JsonElement stackmobElt = responseElt.getAsJsonObject().get("stackmob");
                if (stackmobElt != null && stackmobElt.isJsonObject()) {
                    // Return only the user to be compatible with the old login
                    JsonElement userElt = stackmobElt.getAsJsonObject().get("user");
                    session.setLastUserLoginName(
                            userElt.getAsJsonObject().get(session.getUserIdName()).getAsString());
                    finalResponseBody = userElt.toString().getBytes();
                }
            }
            callback.setDone(requestVerb, requestURL, requestHeaders, requestBody, responseStatusCode,
                    responseHeaders, finalResponseBody);
        }

        @Override
        public void circularRedirect(String originalUrl, Map<String, String> redirectHeaders,
                String redirectBody, String newURL) {
            callback.circularRedirect(originalUrl, redirectHeaders, redirectBody, newURL);
        }
    };
}

From source file:com.stratio.decision.serializer.gson.impl.ColumnNameTypeValueDeserializer.java

License:Apache License

@Override
public ColumnNameTypeValue deserialize(JsonElement element, Type type, JsonDeserializationContext ctx)
        throws JsonParseException {
    final JsonObject object = element.getAsJsonObject();
    String name = null;/*from   ww w.  j  av  a  2 s.c  om*/
    ColumnType columnType = null;
    Object value = null;
    if (object != null && object.has(COLUMN_FIELD) && object.has(TYPE_FIELD)) {
        name = object.get(COLUMN_FIELD).getAsString();
        columnType = ColumnType.valueOf(object.get(TYPE_FIELD).getAsString());

        if (object.has(VALUE_FIELD)) {
            JsonElement jsonValue = object.get(VALUE_FIELD);
            switch (columnType) {
            case BOOLEAN:
                value = jsonValue.getAsBoolean();
                break;
            case DOUBLE:
                value = jsonValue.getAsDouble();
                break;
            case FLOAT:
                value = jsonValue.getAsFloat();
                break;
            case INTEGER:
                value = jsonValue.getAsInt();
                break;
            case LONG:
                value = jsonValue.getAsLong();
                break;
            case STRING:
                value = jsonValue.getAsString();
                break;
            default:
                break;
            }
        } else {
            log.warn("Column with name {} has no value", name);
        }

        if (log.isDebugEnabled()) {
            log.debug("Values obtained into ColumnNameTypeValue deserialization: "
                    + "NAME: {}, VALUE: {}, COLUMNTYPE: {}", name, value, columnType);
        }
    } else {
        log.warn("Error deserializing ColumnNameTypeValue from json. JsonObject is not complete: {}", element);
    }

    return new ColumnNameTypeValue(name, columnType, value);
}

From source file:com.strato.hidrive.api.JSONDataReader.java

License:Apache License

@Override
public int readIntWithName(String name) {
    int defaultValue = 0;
    return get(name, defaultValue, new ElementValue<Integer>() {
        @Override/* ww  w.  j a  v a 2 s  . c  om*/
        public Integer value(JsonElement jsonElement) {
            return jsonElement.getAsInt();
        }
    });
}

From source file:com.tsc9526.monalisa.orm.tools.converters.impl.ArrayTypeConversion.java

License:Open Source License

protected Object convertJsonToArray(JsonArray array, Class<?> type) {
    Object value = null;//  ww w  .j  av  a 2 s.  c  o  m
    if (type == int[].class) {
        int[] iv = new int[array.size()];
        for (int i = 0; i < array.size(); i++) {
            JsonElement e = array.get(i);
            iv[i] = e.getAsInt();
        }
        value = iv;
    } else if (type == float[].class) {
        float[] iv = new float[array.size()];
        for (int i = 0; i < array.size(); i++) {
            JsonElement e = array.get(i);
            iv[i] = e.getAsFloat();
        }
        value = iv;
    } else if (type == long[].class) {
        long[] iv = new long[array.size()];
        for (int i = 0; i < array.size(); i++) {
            JsonElement e = array.get(i);
            iv[i] = e.getAsLong();
        }
        value = iv;
    } else if (type == double[].class) {
        double[] iv = new double[array.size()];
        for (int i = 0; i < array.size(); i++) {
            JsonElement e = array.get(i);
            iv[i] = e.getAsDouble();
        }
        value = iv;
    } else {//String[]
        String[] iv = new String[array.size()];
        for (int i = 0; i < array.size(); i++) {
            JsonElement e = array.get(i);
            if (e.isJsonPrimitive()) {
                iv[i] = e.getAsString();
            } else {
                iv[i] = e.toString();
            }
        }
        value = iv;
    }

    return value;
}