Example usage for com.google.gson JsonElement getAsNumber

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

Introduction

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

Prototype

public Number getAsNumber() 

Source Link

Document

convenience method to get this element as a Number .

Usage

From source file:brooklyn.event.feed.http.JsonFunctions.java

License:Apache License

@SuppressWarnings("unchecked")
public static <T> Function<JsonElement, T> cast(final Class<T> expected) {
    return new Function<JsonElement, T>() {
        @Override//w ww . j  av a 2s.co m
        public T apply(JsonElement input) {
            if (input == null) {
                return (T) null;
            } else if (input.isJsonNull()) {
                return (T) null;
            } else if (expected == boolean.class || expected == Boolean.class) {
                return (T) (Boolean) input.getAsBoolean();
            } else if (expected == char.class || expected == Character.class) {
                return (T) (Character) input.getAsCharacter();
            } else if (expected == byte.class || expected == Byte.class) {
                return (T) (Byte) input.getAsByte();
            } else if (expected == short.class || expected == Short.class) {
                return (T) (Short) input.getAsShort();
            } else if (expected == int.class || expected == Integer.class) {
                return (T) (Integer) input.getAsInt();
            } else if (expected == long.class || expected == Long.class) {
                return (T) (Long) input.getAsLong();
            } else if (expected == float.class || expected == Float.class) {
                return (T) (Float) input.getAsFloat();
            } else if (expected == double.class || expected == Double.class) {
                return (T) (Double) input.getAsDouble();
            } else if (expected == BigDecimal.class) {
                return (T) input.getAsBigDecimal();
            } else if (expected == BigInteger.class) {
                return (T) input.getAsBigInteger();
            } else if (Number.class.isAssignableFrom(expected)) {
                // TODO Will result in a class-cast if it's an unexpected sub-type of Number not handled above
                return (T) input.getAsNumber();
            } else if (expected == String.class) {
                return (T) input.getAsString();
            } else if (expected.isArray()) {
                JsonArray array = input.getAsJsonArray();
                Class<?> componentType = expected.getComponentType();
                if (JsonElement.class.isAssignableFrom(componentType)) {
                    JsonElement[] result = new JsonElement[array.size()];
                    for (int i = 0; i < array.size(); i++) {
                        result[i] = array.get(i);
                    }
                    return (T) result;
                } else {
                    Object[] result = (Object[]) Array.newInstance(componentType, array.size());
                    for (int i = 0; i < array.size(); i++) {
                        result[i] = cast(componentType).apply(array.get(i));
                    }
                    return (T) result;
                }
            } else {
                throw new IllegalArgumentException("Cannot cast json element to type " + expected);
            }
        }
    };
}

From source file:com.cloud.bridge.util.JsonAccessor.java

License:Apache License

public Number getAsNumber(String propPath) {
    JsonElement jsonElement = eval(propPath);
    return jsonElement.getAsNumber();
}

From source file:com.couchbase.cbadmin.client.RebalanceInfo.java

License:Open Source License

public RebalanceInfo(JsonObject obj) throws RestApiException {
    JsonElement e = obj.get("status");
    if (e == null || e.isJsonPrimitive() == false) {
        throw new RestApiException("Expected status string", obj);
    }/*from www .  j  ava  2s . com*/
    String sStatus = e.getAsString();
    if (sStatus.equals("none")) {
        completed = true;

    } else if (sStatus.equals("running")) {
        for (Entry<String, JsonElement> ent : obj.entrySet()) {
            if (ent.getKey().equals("status")) {
                continue;
            }
            JsonObject progressObj;
            if (ent.getValue().isJsonObject() == false) {
                throw new RestApiException("Expected object", ent.getValue());
            }
            progressObj = ent.getValue().getAsJsonObject();
            JsonElement progressNum = progressObj.get("progress");
            if (progressNum.isJsonPrimitive() == false
                    || progressNum.getAsJsonPrimitive().isNumber() == false) {
                throw new RestApiException("Expected 'progress' to be number", progressNum);
            }
            details.put(ent.getKey(), progressNum.getAsNumber().floatValue() * 100);
        }
    }
}

From source file:com.flipkart.android.proteus.toolbox.Utils.java

License:Apache License

public static JsonElement merge(JsonElement oldJson, JsonElement newJson, boolean useCopy, Gson gson) {

    JsonElement newDataElement;/*from www  .  java2 s . com*/
    JsonArray oldArray;
    JsonArray newArray;
    JsonElement oldArrayItem;
    JsonElement newArrayItem;
    JsonObject oldObject;

    if (oldJson == null || oldJson.isJsonNull()) {
        return useCopy ? gson.fromJson(newJson, JsonElement.class) : newJson;
    }

    if (newJson == null || newJson.isJsonNull()) {
        newJson = JsonNull.INSTANCE;
        return newJson;
    }

    if (newJson.isJsonPrimitive()) {
        JsonPrimitive value;
        if (!useCopy) {
            return newJson;
        }
        if (newJson.getAsJsonPrimitive().isBoolean()) {
            value = new JsonPrimitive(newJson.getAsBoolean());
        } else if (newJson.getAsJsonPrimitive().isNumber()) {
            value = new JsonPrimitive(newJson.getAsNumber());
        } else if (newJson.getAsJsonPrimitive().isString()) {
            value = new JsonPrimitive(newJson.getAsString());
        } else {
            value = newJson.getAsJsonPrimitive();
        }
        return value;
    }

    if (newJson.isJsonArray()) {
        if (!oldJson.isJsonArray()) {
            return useCopy ? gson.fromJson(newJson, JsonArray.class) : newJson;
        } else {
            oldArray = oldJson.getAsJsonArray();
            newArray = newJson.getAsJsonArray();

            if (oldArray.size() > newArray.size()) {
                while (oldArray.size() > newArray.size()) {
                    oldArray.remove(oldArray.size() - 1);
                }
            }

            for (int index = 0; index < newArray.size(); index++) {
                if (index < oldArray.size()) {
                    oldArrayItem = oldArray.get(index);
                    newArrayItem = newArray.get(index);
                    oldArray.set(index, merge(oldArrayItem, newArrayItem, useCopy, gson));
                } else {
                    oldArray.add(newArray.get(index));
                }
            }
        }
    } else if (newJson.isJsonObject()) {
        if (!oldJson.isJsonObject()) {
            return useCopy ? gson.fromJson(newJson, JsonObject.class) : newJson;
        } else {
            oldObject = oldJson.getAsJsonObject();
            for (Map.Entry<String, JsonElement> entry : newJson.getAsJsonObject().entrySet()) {
                newDataElement = merge(oldObject.get(entry.getKey()), entry.getValue(), useCopy, gson);
                oldObject.add(entry.getKey(), newDataElement);
            }
        }
    } else {
        return useCopy ? gson.fromJson(newJson, JsonElement.class) : newJson;
    }

    return oldJson;
}

From source file:com.getperka.flatpack.codexes.BooleanCodex.java

License:Apache License

@Override
public Boolean readNotNull(JsonElement element, DeserializationContext context) {
    return element.getAsJsonPrimitive().isNumber() ? element.getAsNumber().intValue() != 0
            : element.getAsBoolean();/* w w w . ja v  a  2s .  c om*/
}

From source file:com.github.zhizheng.json.JsonSchemaGeneratorImpl.java

License:Apache License

/**
 * ? JsonElement? Json Schema /*from w ww .  j av  a2 s. c  om*/
 * 
 * @param jsonElement
 * @param elementName
 * @param isFirstLevel
 * @param required
 * @return
 */
private JsonObject makeSchemaElement(JsonElement jsonElement, String elementName, boolean isFirstLevel,
        JsonArray required) {
    JsonObject jsonSchemaObject = new JsonObject();

    // id, $schema
    if (isFirstLevel) {
        if (jsonSchemaConfig.isPrintId()) {
            jsonSchemaObject.addProperty(JsonSchemaKeywords.ID.toString(), jsonSchemaConfig.getId());
        }
        jsonSchemaObject.addProperty(JsonSchemaKeywords.SCHEMA.toString(), jsonSchemaConfig.getVersion());
    } else {
        if (jsonSchemaConfig.isPrintId()) {
            jsonSchemaObject.addProperty(JsonSchemaKeywords.ID.toString(), "/" + elementName);
        }
    }

    // title
    if (jsonSchemaConfig.isPrintTitle()) {
        jsonSchemaObject.addProperty(JsonSchemaKeywords.TITLE.toString(), elementName);// jsonSchemaConfig.getTitle()
    }

    // description
    if (jsonSchemaConfig.isPrintDescription()) {
        jsonSchemaObject.addProperty(JsonSchemaKeywords.DESCRIPTION.toString(),
                jsonSchemaConfig.getDescription());
    }

    // type
    String jsonElementType = JsonValueTypes.getJsonValueType(jsonElement);
    jsonSchemaObject.addProperty(JsonSchemaKeywords.TYPE.toString(), jsonElementType);
    if (jsonElementType.equals(JsonValueTypes.STRING.toString())) {// string
        if (jsonSchemaConfig.isPrintMinLength()) {
            jsonSchemaObject.addProperty(JsonSchemaKeywords.MINLENGTH.toString(),
                    jsonSchemaConfig.getMinLength());
        }
        if (jsonSchemaConfig.isPrintMaxLength()) {
            jsonSchemaObject.addProperty(JsonSchemaKeywords.MAXLENGTH.toString(),
                    jsonSchemaConfig.getMaxLength());
        }
        if (jsonSchemaConfig.isPrintDefault()) {
            jsonSchemaObject.addProperty(JsonSchemaKeywords.DEFAULT.toString(),
                    jsonSchemaConfig.isDefaultFromJson() ? jsonElement.getAsString()
                            : jsonSchemaConfig.getDefaultString());
        }
    }
    if (jsonElementType.equals(JsonValueTypes.NUMBER.toString())) {// number
        if (jsonSchemaConfig.isPrintMinimum()) {
            jsonSchemaObject.addProperty(JsonSchemaKeywords.MINIMUM.toString(), jsonSchemaConfig.getMinimum());
        }
        if (jsonSchemaConfig.isPrintMaximum()) {
            jsonSchemaObject.addProperty(JsonSchemaKeywords.MAXIMUM.toString(), jsonSchemaConfig.getMaximum());
        }
        if (jsonSchemaConfig.isPrintExclusiveMinimum()) {
            if (!jsonSchemaConfig.isPrintMinimum()) {
                jsonSchemaObject.addProperty(JsonSchemaKeywords.MINIMUM.toString(),
                        jsonSchemaConfig.getMinimum());
            }
            jsonSchemaObject.addProperty(JsonSchemaKeywords.EXCLUSIVEMINIMUM.toString(),
                    jsonSchemaConfig.isExclusiveMinimum());
        }
        if (jsonSchemaConfig.isPrintExclusiveMaximum()) {
            if (!jsonSchemaConfig.isPrintMaximum()) {
                jsonSchemaObject.addProperty(JsonSchemaKeywords.MAXIMUM.toString(),
                        jsonSchemaConfig.getMaximum());
            }
            jsonSchemaObject.addProperty(JsonSchemaKeywords.EXCLUSIVEMAXIMUM.toString(),
                    jsonSchemaConfig.isExclusiveMaximum());
        }
        if (jsonSchemaConfig.isPrintDefault()) {
            jsonSchemaObject.addProperty(JsonSchemaKeywords.DEFAULT.toString(),
                    jsonSchemaConfig.isDefaultFromJson() ? jsonElement.getAsNumber()
                            : jsonSchemaConfig.getDefaultNumber());
        }
    }

    // required && V3
    if (jsonSchemaConfig.isPrintRequired()
            && JsonSchemaVersions.V3.toString().equals(jsonSchemaConfig.getVersion())) {// V3 required  boolean ???
        jsonSchemaObject.addProperty(JsonSchemaKeywords.REQUIRED.toString(), jsonSchemaConfig.isRequired());
    }
    // required && V4
    if (jsonSchemaConfig.isPrintRequired()
            && JsonSchemaVersions.V4.toString().equals(jsonSchemaConfig.getVersion())
            && (jsonElementType.equals(JsonValueTypes.STRING.toString())
                    || jsonElementType.equals(JsonValueTypes.NUMBER.toString())
                    || jsonElementType.equals(JsonValueTypes.INTEGER.toString())
                    || jsonElementType.equals(JsonValueTypes.BOOLEAN.toString()))) {// V4 required  array ? object 
        required.add(elementName);
    }

    // properties, items
    JsonArray newRequired = new JsonArray();
    if (jsonElementType.equals(JsonValueTypes.OBJECT.toString())
            && !jsonElement.getAsJsonObject().entrySet().isEmpty()) {// object.properties
        JsonObject propertiesObject = new JsonObject();
        for (Map.Entry<String, JsonElement> propertyElemement : jsonElement.getAsJsonObject().entrySet()) {
            propertiesObject.add(propertyElemement.getKey(), makeSchemaElement(propertyElemement.getValue(),
                    propertyElemement.getKey(), false, newRequired));
        }
        jsonSchemaObject.add(JsonSchemaKeywords.PROPERTIES.toString(), propertiesObject);
    } else if (jsonElementType.equals(JsonValueTypes.ARRAY.toString())
            && jsonElement.getAsJsonArray().size() > 0) {// array.items
        JsonArray jsonArray = jsonElement.getAsJsonArray();
        jsonSchemaObject.add(JsonSchemaKeywords.ITEMS.toString(),
                makeSchemaElement(jsonArray.get(0), "0", false, new JsonArray()));

    }

    // required && V4
    if (jsonElementType.equals(JsonValueTypes.OBJECT.toString())
            && JsonSchemaVersions.V4.toString().equals(jsonSchemaConfig.getVersion())) {// object.required
        jsonSchemaObject.add(JsonSchemaKeywords.REQUIRED.toString(), newRequired);
    }

    // minitems , uniqueitems
    if (jsonElementType.equals(JsonValueTypes.ARRAY.toString())) {// array
        if (jsonSchemaConfig.isPrintMinItems()) {// array.minitems
            jsonSchemaObject.addProperty(JsonSchemaKeywords.MINITEMS.toString(),
                    jsonSchemaConfig.getMinItems());
        }
        if (jsonSchemaConfig.isPrintUniqueItems()) {// array.uniqueitems
            jsonSchemaObject.addProperty(JsonSchemaKeywords.UNIQUEITEMS.toString(),
                    jsonSchemaConfig.isUniqueItems());
        }
    }

    return jsonSchemaObject;
}

From source file:com.ibm.iotf.devicemgmt.device.resource.NumberResource.java

License:Open Source License

/**
 * Updates the value of this resource with the given Json value
 *///from   w  w  w. j a  v  a 2  s .c  o m
@Override
public int update(JsonElement json, boolean fireEvent) {
    this.setValue(json.getAsNumber(), fireEvent);
    return this.getRC();
}

From source file:com.jcwhatever.nucleus.storage.JsonDataNode.java

License:MIT License

@Override
@Nullable//w  w w  . ja  va  2s.c o  m
protected Object getNumberObject(String keyPath) {
    JsonElement element = getJsonElement(keyPath);
    if (element == null || element.isJsonObject())
        return null;

    return element.getAsNumber();
}

From source file:com.wialon.core.Session.java

License:Apache License

/**
 * Handle item search result from server
 *//*  w w w  .j a va  2  s.c  om*/
private void onSearchItemResult(String result, ResponseHandler callback) {
    if (result == null) {
        // error
        callback.onFailure(6, null);
        return;
    }
    //Send string result
    callback.onSuccess(result);
    // create result
    // construct item
    JsonElement responseJson = jsonParser.parse(result);
    if (responseJson == null || !responseJson.isJsonObject()) {
        return;
    }
    JsonElement itemJson = responseJson.getAsJsonObject().get("item");
    JsonElement itemFlags = responseJson.getAsJsonObject().get("flags");
    if (itemJson == null || !itemJson.isJsonObject() || itemFlags == null || itemFlags.getAsNumber() == null) {
        return;
    }
    if (callback instanceof SearchResponseHandler)
        ((SearchResponseHandler) callback)
                .onSuccessSearch(constructItem(itemJson.getAsJsonObject(), itemFlags.getAsLong()));
}

From source file:com.wialon.core.Session.java

License:Apache License

/**
 * Handle items search result from server
 * callback require 2nd parameter in form: {items: [], dataFlags: 0x10, totalItemsCount: 100, indexFrom: 0, indexTo: 9, searchSpec: {...}}
 *//*ww w .  ja  va2 s  .  c  o  m*/
private void onSearchItemsResult(String result, ResponseHandler callback) {
    if (result == null) {
        callback.onFailure(6, null);
        return;
    }
    //Send string result
    callback.onSuccess(result);
    // construct items
    JsonElement responseJson = jsonParser.parse(result);
    if (responseJson == null || !responseJson.isJsonObject()) {
        return;
    }
    JsonElement dataFlags = responseJson.getAsJsonObject().get("dataFlags");
    JsonElement itemsJson = responseJson.getAsJsonObject().get("items");
    if (itemsJson == null || !itemsJson.isJsonArray() || dataFlags == null || dataFlags.getAsNumber() == null) {
        return;
    }
    JsonArray responseItems = itemsJson.getAsJsonArray();
    Item[] items = new Item[responseItems.size()];
    for (int i = 0; i < responseItems.size(); i++) {
        try {
            JsonObject itemData = responseItems.get(i).getAsJsonObject();
            Item item = constructItem(itemData, dataFlags.getAsLong());
            items[i] = item;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    if (callback instanceof SearchResponseHandler)
        ((SearchResponseHandler) callback).onSuccessSearch(items);
}