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.adr.datasql.orm.KindResultsJson.java

License:Apache License

@Override
public Integer getInt(String columnName) throws DataLinkException {
    JsonElement element = json.get(columnName);
    return element == null || element.isJsonNull() ? null : element.getAsInt();
}

From source file:com.antew.redditinpictures.library.gson.BooleanDeserializer.java

License:Apache License

@Override
public Boolean deserialize(JsonElement element, Type type, JsonDeserializationContext context)
        throws JsonParseException {
    return element.getAsInt() == 1 ? true : false;
}

From source file:com.arangodb.BaseArangoDriver.java

License:Apache License

/**
 * Checks the Http response for database or server errors
 * @param res the response of the database
 * @return The Http status code/*  w ww  .java2 s  .  c  o m*/
 * @throws ArangoException if any error happened
 */
private int checkServerErrors(HttpResponseEntity res) throws ArangoException {
    int statusCode = res.getStatusCode();
    if (statusCode >= 400) { // always throws ArangoException
        DefaultEntity defaultEntity = new DefaultEntity();
        if (res.getText() != null && !res.getText().equalsIgnoreCase("") && statusCode != 500) {
            JsonParser jsonParser = new JsonParser();
            JsonElement jsonElement = jsonParser.parse(res.getText());
            JsonObject jsonObject = jsonElement.getAsJsonObject();
            JsonElement errorMessage = jsonObject.get("errorMessage");
            defaultEntity.setErrorMessage(errorMessage.getAsString());
            JsonElement errorNumber = jsonObject.get("errorNum");
            defaultEntity.setErrorNumber(errorNumber.getAsInt());
        } else {
            String statusPhrase = "";
            switch (statusCode) {
            case 400:
                statusPhrase = "Bad Request";
                break;
            case 401:
                statusPhrase = "Unauthorized";
                break;
            case 403:
                statusPhrase = "Forbidden";
                break;
            case 404:
                statusPhrase = "Not Found";
                break;
            case 405:
                statusPhrase = "Method Not Allowed";
                break;
            case 406:
                statusPhrase = "Not Acceptable";
                break;
            case 407:
                statusPhrase = "Proxy Authentication Required";
                break;
            case 408:
                statusPhrase = "Request Time-out";
                break;
            case 409:
                statusPhrase = "Conflict";
                break;
            case 500:
                statusPhrase = "Internal Server Error";
                break;
            default:
                statusPhrase = "unknown error";
                break;
            }

            defaultEntity.setErrorMessage(statusPhrase);
            if (statusCode == 500) {
                defaultEntity.setErrorMessage(statusPhrase + ": " + res.getText());
            }
        }

        defaultEntity.setCode(statusCode);
        defaultEntity.setStatusCode(statusCode);
        defaultEntity.setError(true);
        ArangoException arangoException = new ArangoException(defaultEntity);
        arangoException.setCode(statusCode);
        throw arangoException;
    }

    return statusCode;
}

From source file:com.asakusafw.testdriver.json.JsonObjectDriver.java

License:Apache License

@Override
public void intProperty(PropertyName name, JsonObject context) throws IOException {
    JsonElement prop = property(context, name);
    if (prop == null) {
        return;//ww w .j  av  a2  s.  c  o m
    }
    builder.add(name, prop.getAsInt());
}

From source file:com.azure.webapi.MobileServiceJsonTable.java

License:Open Source License

/**
 * Removes the Id property from a JsonObject
 * // w w w. jav a  2s.c  o  m
 * @param json
 *            The JsonObject to modify
 */
private void removeIdFromJson(final JsonObject json) {
    // Remove id property if exists
    String[] idPropertyNames = new String[] { "id", "Id", "iD", "ID" };
    for (int i = 0; i < 4; i++) {
        String idProperty = idPropertyNames[i];
        if (json.has(idProperty)) {
            JsonElement idElement = json.get(idProperty);
            if (isValidTypeId(idElement) && idElement.getAsInt() != 0) {
                throw new InvalidParameterException(
                        "The entity to insert should not have " + idProperty + " property defined");
            }

            json.remove(idProperty);
        }
    }
}

From source file:com.azure.webapi.MobileServiceTableBase.java

License:Open Source License

/**
 * Gets the id property from a given element
 * //  ww  w.j a v a 2s. c  om
 * @param element
 *            The element to use
 * @return The id of the element
 */
protected int getObjectId(Object element) {
    if (element == null) {
        throw new InvalidParameterException("Element cannot be null");
    } else if (element instanceof Integer) {
        return ((Integer) element).intValue();
    }

    JsonObject jsonObject;
    if (element instanceof JsonObject) {
        jsonObject = (JsonObject) element;
    } else {
        jsonObject = mClient.getGsonBuilder().create().toJsonTree(element).getAsJsonObject();
    }

    updateIdProperty(jsonObject);

    JsonElement idProperty = jsonObject.get("id");
    if (idProperty instanceof JsonNull || idProperty == null) {
        throw new InvalidParameterException("Element must contain id property");
    }

    return idProperty.getAsInt();
}

From source file:com.b12kab.tmdblibrary.AccountStateDeserializer.java

License:Apache License

@Override
public AccountState deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {
    AccountState accountState = new AccountState();
    String convertVariable = "";
    JsonObject obj = (JsonObject) json;//from ww w.  jav a 2  s.  com
    JsonElement element;
    JsonElement ratingElement;
    JsonPrimitive rating;
    try {
        convertVariable = "id";
        element = obj.get("id");
        if (element != null) {
            if (element.isJsonPrimitive()) {
                if (element.getAsJsonPrimitive().isNumber()) {
                    accountState.setId(element.getAsInt());
                }
            }
        }

        convertVariable = "favorite";
        element = obj.get("favorite");
        if (element != null) {
            if (element.isJsonPrimitive()) {
                if (element.getAsJsonPrimitive().isBoolean()) {
                    accountState.setFavorite(element.getAsBoolean());
                }
            }
        }

        accountState.setRated(null);
        convertVariable = "rated";
        element = obj.get("rated");
        if (element != null) {
            if (element.isJsonObject()) {
                if (element.getAsJsonObject().has("value")) {
                    ratingElement = element.getAsJsonObject().get("value");
                    if (ratingElement.isJsonPrimitive()) {
                        //                        rating
                        if (ratingElement.getAsJsonPrimitive().isNumber()) {
                            accountState.setRated(ratingElement.getAsFloat());
                        }
                    }
                }
            }
        }

        convertVariable = "watchlist";
        element = obj.get("watchlist");
        if (element != null) {
            if (element.isJsonPrimitive()) {
                if (element.getAsJsonPrimitive().isBoolean()) {
                    accountState.setWatchlist(element.getAsBoolean());
                }
            }
        }
    } catch (NullPointerException npe) {
        Log.e(TAG, "Processing " + convertVariable + " response from Tmdb, NullPointerException occurred"
                + npe.toString());
        return null;
    } catch (NumberFormatException npe) {
        Log.e(TAG, "Processing " + convertVariable + " response from Tmdb, NumberFormatException occurred"
                + npe.toString());
        return null;
    } catch (IllegalStateException ise) {
        Log.e(TAG, "Processing " + convertVariable + " response from Tmdb, IllegalStateException occurred"
                + ise.toString());
    }

    return accountState;
}

From source file:com.b12kab.tmdblibrary.TmdbHelper.java

License:Apache License

/**
 * Create a {@link com.google.gson.GsonBuilder} and register all of the custom types needed in
 * order to properly deserialize complex TMDb-specific types.
 *
 * @return Assembled GSON builder instance.
 */// w ww .  ja  v  a  2s .c  om
public static GsonBuilder getGsonBuilder() {
    GsonBuilder builder = new GsonBuilder();

    // class types
    builder.registerTypeAdapter(AccountState.class, new AccountStateDeserializer());
    builder.registerTypeAdapter(Integer.class, new JsonDeserializer<Integer>() {
        @Override
        public Integer deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
                throws JsonParseException {
            try {
                return Integer.valueOf(json.getAsInt());
            } catch (NumberFormatException e) {
                return null;
            }
        }
    });
    builder.registerTypeAdapter(Date.class, new JsonDeserializer<Date>() {
        @Override
        public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
                throws JsonParseException {

            try {
                return JSON_STRING_DATE.parse(json.getAsString());
            } catch (ParseException e) {
                return null;
            }
        }
    });

    return builder;
}

From source file:com.balajeetm.mystique.core.lever.MystiqueLever.java

License:Open Source License

/**
 * Sets the field of a json source./*from w ww  .java 2  s  .co  m*/
 *
 * @param resultWrapper the json object that wraps the result json. The result is wrapped to
 *     ensure it passed across by reference and fields are updated appropriately
 * @param to the jPath json array defining the full qualified json path to the destination field
 *     where the value must be set
 * @param value the json value that needs to be set to the destination. This can be an Object,
 *     Array or a Primitive
 * @param aces the pre-processed dependency list in the form of key value pair (json)
 * @param optional the flag that determines if a null value must be set in the destination. If
 *     optional is TRUE, null values are not set in the destination
 * @return the json result wraper object which contains the result in the field called "result"
 */
public JsonObject set(JsonObject resultWrapper, JsonArray to, JsonElement value, JsonObject aces,
        Boolean optional) {

    /**
     * Holding a mutex on result wrapper and not making the method synchronized because, when
     * multiple unrelated threads might be calling mystique for transformation. The resource of
     * contention is only the result wrapper
     */
    synchronized (resultWrapper) {
        if (optional && isNull(value)) {
            // Do Not update result wrapper
            return resultWrapper;
        }
        if (isNotNull(to)) {
            JsonElement result = resultWrapper.get(MystiqueConstants.RESULT);
            JsonElement field = result;
            if (to.size() > 0) {
                JsonElement previousPath = null;
                JsonElement currentPath = null;
                Iterator<JsonElement> iterator = to.iterator();
                if (iterator.hasNext()) {
                    previousPath = getPathField(iterator.next(), aces);
                }

                while (iterator.hasNext()) {
                    currentPath = getPathField(iterator.next(), aces);

                    // get the field
                    field = getRepleteField(field, previousPath, currentPath);
                    result = updateResult(result, field);
                    field = isNumber(previousPath) ? field.getAsJsonArray().get(previousPath.getAsInt())
                            : field.getAsJsonObject().get(previousPath.getAsString());
                    previousPath = currentPath;
                }

                field = setField(field, previousPath, value);
                result = updateResult(result, field);
            } else {
                result = merge(result, value);
            }
            resultWrapper.add(MystiqueConstants.RESULT, result);
        }
        return resultWrapper;
    }
}

From source file:com.balajeetm.mystique.util.gson.lever.JsonLever.java

License:Open Source License

/**
 * Gets the json element in the specified jpath.
 *
 * @param source the source/*from w  w  w .ja  va  2  s . c o m*/
 * @param jpath the fully qualified json path to the field required. eg get({'a': {'b': {'c': [1,
 *     2, 3, 4]}}}, ["a", "b" "c", 1]) is '2'. Array indexes need to be specified as numerals.
 *     Strings are always presumed to be field names.
 * @return the json element returns 'Null' for any invalid path return the source if the input
 *     jpath is '.'
 */
public JsonElement get(JsonElement source, JsonArray jpath) {
    JsonElement result = JsonNull.INSTANCE;
    if (isNotNull(jpath)) {
        result = source;
        for (JsonElement path : jpath) {
            try {
                if (isNumber(path)) {
                    result = result.getAsJsonArray().get(path.getAsInt());
                } else {
                    result = result.getAsJsonObject().get(path.getAsString());
                }
            } catch (Exception e) {
                return JsonNull.INSTANCE;
            }
        }
    }

    return result;
}