Example usage for com.google.gson JsonElement getAsLong

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

Introduction

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

Prototype

public long getAsLong() 

Source Link

Document

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

Usage

From source file:com.relayrides.pushy.apns.DateAsTimeSinceEpochTypeAdapter.java

License:Open Source License

@Override
public Date deserialize(final JsonElement json, final Type typeOfT, final JsonDeserializationContext context)
        throws JsonParseException {
    final Date date;

    if (json.isJsonPrimitive()) {
        date = new Date(this.timeUnit.toMillis(json.getAsLong()));
    } else if (json.isJsonNull()) {
        date = null;/*from www. ja  v a  2s  .  c  om*/
    } else {
        throw new JsonParseException(
                "Dates represented as time since the epoch must either be numbers or null.");
    }

    return date;
}

From source file:com.sandata.lab.common.utils.data.adapter.CustomJodaDateTimeAdapter.java

License:Open Source License

/**
 * UI will send the Date in Milliseconds from Jan 1 1970 via javascript new Date().getTime()
 *
 * @param jsonElement//from  w  w  w  .  j  a v  a 2  s. c o  m
 * @param type
 * @param jsonDeserializationContext
 * @return
 * @throws com.google.gson.JsonParseException
 */

@Override
public DateTime deserialize(JsonElement jsonElement, Type type,
        JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {

    try {
        // Convert jsonElement string to JODA DateTime (if in the given format by Javascript new Date().toJSON() method.
        Date date = new SimpleDateFormat("yyyy-MM-dd h:mm aa").parse(jsonElement.getAsString());

        // Conversion successful, return a Joda DateTime object
        return new DateTime(date.getTime());
    } catch (Exception e) {
        // If the jsonElement is the time in milliseconds from Jan 1 1970 try to convert...
        return new DateTime(jsonElement.getAsLong());
    }
}

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://from   w  w  w  .jav  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.solidfire.jsvcgen.serialization.OptionalAdapter.java

License:Open Source License

/**
 * Deserializes an Optional object./*w  ww  . j  a v a  2s . c om*/
 *
 * @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.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   www .  j  a  v  a  2s  .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 long readLongWithName(String name) {
    long defaultValue = 0L;
    return get(name, defaultValue, new ElementValue<Long>() {
        @Override//from  ww w .j a  v  a2 s  .c om
        public Long value(JsonElement jsonElement) {
            return jsonElement.getAsLong();
        }
    });
}

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;//w ww . ja v  a2  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;
}

From source file:com.ushahidi.android.data.api.DateDeserializer.java

License:Open Source License

@Override
public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {
    final SimpleDateFormat PARSER = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX", Locale.getDefault());
    try {/*from  w w w. j ava 2 s  .  com*/
        if (TextUtils.isDigitsOnly(json.getAsString())) {
            return new Date(new java.util.Date(json.getAsLong()));
        }
        return new Date(PARSER.parse(json.getAsString()));
    } catch (ParseException e) {
        throw new JsonParseException(e);
    }
}

From source file:com.ushahidi.platform.mobile.app.data.api.DateDeserializer.java

License:Open Source License

@Override
public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {
    final SimpleDateFormat parser = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX", Locale.getDefault());
    try {/*from ww w  . ja  v  a 2 s  .co  m*/
        if (TextUtils.isDigitsOnly(json.getAsString())) {
            return new Date(new java.util.Date(json.getAsLong()));
        }
        return new Date(parser.parse(json.getAsString()));
    } catch (ParseException e) {
        throw new JsonParseException(e);
    }
}

From source file:com.vmware.admiral.compute.container.maintenance.ContainerStatsEvaluator.java

License:Open Source License

private static void setNetworkUsage(ContainerStats state, Map<String, JsonElement> stats) {
    try {/*w  w  w  .  j  a  v  a  2 s .  com*/
        JsonElement jsonElement = stats.get("networks");
        if (jsonElement == null) {
            return;
        }
        JsonObject networks = jsonElement.getAsJsonObject();
        if (networks == null) {
            return;
        }
        Set<Entry<String, JsonElement>> entrySet = networks.entrySet();
        if (entrySet == null) {
            return;
        }

        NetworkTraffic summedTraffic = entrySet.stream().map(entry -> {

            JsonObject network = entry.getValue().getAsJsonObject();
            NetworkTraffic result = new NetworkTraffic();

            if (network != null) {
                JsonElement netInValue = network.get("rx_bytes");
                if (netInValue != null) {
                    result.networkIn = netInValue.getAsLong();
                }

                JsonElement netOutValue = network.get("tx_bytes");
                if (netOutValue != null) {
                    result.networkOut += netOutValue.getAsLong();
                }
            }

            return result;

        }).reduce(new NetworkTraffic(), (t1, t2) -> {

            return new NetworkTraffic(t1.networkIn + t2.networkIn, t1.networkOut + t2.networkOut);
        });

        state.networkIn = summedTraffic.networkIn;
        state.networkOut = summedTraffic.networkOut;

    } catch (Exception e) {
        Utils.logWarning("Error during container stats network usage parsing: %s", Utils.toString(e));
    }
}