Example usage for com.google.gson JsonPrimitive isNumber

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

Introduction

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

Prototype

public boolean isNumber() 

Source Link

Document

Check whether this primitive contains a Number.

Usage

From source file:ch.cern.db.flume.sink.elasticsearch.serializer.JSONtoElasticSearchEventSerializer.java

License:GNU General Public License

private void appendBody(XContentBuilder builder, Event event) throws IOException {
    JsonParser parser = new JsonParser();

    JsonObject json = parser.parse(new String(event.getBody())).getAsJsonObject();

    for (Entry<String, JsonElement> property : json.entrySet()) {

        if (property.getValue().isJsonNull()) {
            builder.nullField(property.getKey());

            continue;
        }/*from   w  w  w  . j  av a2s .  c o  m*/

        if (!property.getValue().isJsonPrimitive()) {
            builder.field(property.getKey(), property.getValue());

            continue;
        }

        JsonPrimitive primitiveValue = (JsonPrimitive) property.getValue();

        if (primitiveValue.isBoolean())
            builder.field(property.getKey(), primitiveValue.getAsBoolean());
        else if (primitiveValue.isNumber())
            if (primitiveValue.getAsString().indexOf('.') != -1)
                builder.field(property.getKey(), primitiveValue.getAsNumber().doubleValue());
            else
                builder.field(property.getKey(), primitiveValue.getAsNumber().longValue());
        else if (primitiveValue.isString())
            builder.field(property.getKey(), primitiveValue.getAsString());
    }
}

From source file:com.addthis.hydra.task.source.bundleizer.GsonBundleizer.java

License:Apache License

public ValueObject fromGson(JsonElement gson) {
    if (gson.isJsonNull()) {
        return null;
    } else if (gson.isJsonObject()) {
        JsonObject object = gson.getAsJsonObject();
        ValueMap map = ValueFactory.createMap();
        for (Map.Entry<String, JsonElement> entry : object.entrySet()) {
            map.put(entry.getKey(), fromGson(entry.getValue()));
        }// w  w w . j  a  v a2  s  .  co  m
        return map;
    } else if (gson.isJsonArray()) {
        JsonArray gsonArray = gson.getAsJsonArray();
        ValueArray valueArray = ValueFactory.createArray(gsonArray.size());
        for (JsonElement arrayElement : gsonArray) {
            valueArray.add(fromGson(arrayElement));
        }
        return valueArray;
    } else {
        JsonPrimitive primitive = gson.getAsJsonPrimitive();
        if (primitive.isNumber()) {
            return ValueFactory.create(primitive.getAsDouble());
        } else {
            return ValueFactory.create(primitive.getAsString());
        }
    }
}

From source file:com.adobe.acs.commons.remoteassets.impl.RemoteAssetsNodeSyncImpl.java

License:Apache License

/**
 * Set generic array property for a resource, based on an array found in the retrieved JSON.
 *
 * @param jsonArray JsonArray/*from w w  w . j a  v a2  s  .  c  om*/
 * @param key String
 * @param resource Resource
 * @throws RepositoryException exception
 */
private void setNodeSimpleArrayProperty(final JsonArray jsonArray, final String key, final Resource resource)
        throws RepositoryException {
    JsonPrimitive firstVal = jsonArray.get(0).getAsJsonPrimitive();

    try {
        Object[] values;
        if (firstVal.isBoolean()) {
            values = new Boolean[jsonArray.size()];
            for (int i = 0; i < jsonArray.size(); i++) {
                values[i] = jsonArray.get(i).getAsBoolean();
            }
        } else if (DECIMAL_REGEX.matcher(firstVal.getAsString()).matches()) {
            values = new BigDecimal[jsonArray.size()];
            for (int i = 0; i < jsonArray.size(); i++) {
                values[i] = jsonArray.get(i).getAsBigDecimal();
            }
        } else if (firstVal.isNumber()) {
            values = new Long[jsonArray.size()];
            for (int i = 0; i < jsonArray.size(); i++) {
                values[i] = jsonArray.get(i).getAsLong();
            }
        } else {
            values = new String[jsonArray.size()];
            for (int i = 0; i < jsonArray.size(); i++) {
                values[i] = jsonArray.get(i).getAsString();
            }
        }

        ValueMap resourceProperties = resource.adaptTo(ModifiableValueMap.class);
        resourceProperties.put(key, values);
        LOG.trace("Array property '{}' added for resource '{}'", key, resource.getPath());
    } catch (Exception e) {
        LOG.error("Unable to assign property '{}' to resource '{}'", key, resource.getPath(), e);
    }
}

From source file:com.adobe.acs.commons.remoteassets.impl.RemoteAssetsNodeSyncImpl.java

License:Apache License

/**
 * Set a simple resource property from the fetched JSON.
 *
 * @param value Object/*from ww w . ja v a2s  .c  o  m*/
 * @param key String
 * @param resource Resource
 * @throws RepositoryException exception
 */
private void setNodeSimpleProperty(final JsonPrimitive value, final String key, final Resource resource)
        throws RepositoryException {
    ValueMap resourceProperties = resource.adaptTo(ModifiableValueMap.class);
    if (value.isString() && DATE_REGEX.matcher(value.getAsString()).matches()) {
        try {
            resourceProperties.put(key,
                    GregorianCalendar.from(ZonedDateTime.parse(value.getAsString(), DATE_TIME_FORMATTER)));
        } catch (DateTimeParseException e) {
            LOG.warn("Unable to parse date '{}' for property:resource '{}'.", value,
                    key + ":" + resource.getPath());
        }
    } else if (value.isString() && DECIMAL_REGEX.matcher(value.getAsString()).matches()) {
        resourceProperties.put(key, value.getAsBigDecimal());
    } else if (value.isBoolean()) {
        resourceProperties.put(key, value.getAsBoolean());
    } else if (value.isNumber()) {
        if (DECIMAL_REGEX.matcher(value.getAsString()).matches()) {
            resourceProperties.put(key, value.getAsBigDecimal());
        } else {
            resourceProperties.put(key, value.getAsLong());
        }
    } else if (value.isJsonNull()) {
        resourceProperties.remove(key);
    } else {
        resourceProperties.put(key, value.getAsString());
    }

    LOG.trace("Property '{}' added for resource '{}'.", key, resource.getPath());
}

From source file:com.balajeetm.mystique.core.module.GsonSerialiser.java

License:Open Source License

@Override
public void serialize(JsonElement value, JsonGenerator gen, SerializerProvider provider) throws IOException {
    if (jsonLever.isNull(value)) {
        gen.writeNull();//from www. j a v a2 s  .  c  o m
    } else if (jsonLever.isObject(value)) {
        gen.writeStartObject();
        JsonObject jsonObject = value.getAsJsonObject();
        for (Entry<String, JsonElement> entry : jsonObject.entrySet()) {
            gen.writeFieldName(entry.getKey());
            serialize(entry.getValue(), gen, provider);
        }
        gen.writeEndObject();
    } else if (jsonLever.isArray(value)) {
        gen.writeStartArray();
        JsonArray jsonArray = value.getAsJsonArray();
        for (JsonElement jsonElement : jsonArray) {
            serialize(jsonElement, gen, provider);
        }
        gen.writeEndArray();
    } else if (jsonLever.isPrimitive(value)) {
        JsonPrimitive jsonPrimitive = value.getAsJsonPrimitive();
        if (jsonPrimitive.isBoolean()) {
            gen.writeBoolean(jsonPrimitive.getAsBoolean());
        }
        if (jsonPrimitive.isNumber()) {
            Number nnode = jsonPrimitive.getAsNumber();
            if (nnode instanceof LazilyParsedNumber) {
                gen.writeNumber(nnode.toString());
            } else if (nnode instanceof Integer) {
                gen.writeNumber(nnode.intValue());
            } else if (nnode instanceof Short) {
                gen.writeNumber(nnode.shortValue());
            } else if (nnode instanceof BigInteger || nnode instanceof Long) {
                gen.writeNumber(nnode.longValue());
            } else if (nnode instanceof Float) {
                gen.writeNumber(nnode.floatValue());
            } else if (nnode instanceof Double || nnode instanceof BigDecimal) {
                gen.writeNumber(nnode.doubleValue());
            }
        }
        if (jsonPrimitive.isString()) {
            gen.writeString(jsonPrimitive.getAsString());
        }
    }
}

From source file:com.bzcentre.dapiPush.MeetingPayload.java

License:Open Source License

private Object extractAps(JsonElement in) {
    if (in == null || in.isJsonNull())
        return null;

    if (in.isJsonArray()) {
        List<Object> list = new ArrayList<>();
        JsonArray arr = in.getAsJsonArray();
        for (JsonElement anArr : arr) {
            list.add(extractAps(anArr));
        }/*www. j a v a 2 s  . c  o  m*/
        return list;
    } else if (in.isJsonObject()) {
        Map<String, Object> map = new LinkedTreeMap<>();
        JsonObject obj = in.getAsJsonObject();
        Set<Map.Entry<String, JsonElement>> entitySet = obj.entrySet();
        for (Map.Entry<String, JsonElement> entry : entitySet) {
            map.put(entry.getKey(), extractAps(entry.getValue()));
            NginxClojureRT.log.debug(TAG + entry.getKey() + "=>" + map.get(entry.getKey()) + "=>"
                    + map.get(entry.getKey()).getClass().getTypeName());
            switch (entry.getKey()) {
            case "dapi":
                this.setDapi(map.get(entry.getKey()));
                break;
            case "acme1":
                this.setAcme1(map.get(entry.getKey()));
                break;
            case "acme2":
                this.setAcme2(map.get(entry.getKey()));
                break;
            case "acme3":
                this.setAcme3(map.get(entry.getKey()));
                break;
            case "acme4":
                this.setAcme4(map.get(entry.getKey()));
                break;
            case "acme5":
                this.setAcme5(map.get(entry.getKey()));
                break;
            case "acme6":
                this.setAcme6(map.get(entry.getKey()));
                break;
            case "acme7":
                this.setAcme7(map.get(entry.getKey()));
                break;
            case "acme8":
                this.setAcme8(map.get(entry.getKey()));
                break;
            case "aps":
                NginxClojureRT.log.debug(TAG + "aps initialized");
                break;
            case "badge":
                this.getAps().setBadge(map.get(entry.getKey()));
                break;
            case "sound":
                this.getAps().setSound(map.get(entry.getKey()));
                break;
            case "alert":
                NginxClojureRT.log.debug(TAG + "alert initialized");
                break;
            case "title":
                this.getAps().getAlert().setTitle(map.get(entry.getKey()));
                break;
            case "body":
                this.getAps().getAlert().setBody(map.get(entry.getKey()));
                break;
            case "action-loc-key":
                this.getAps().getAlert().setActionLocKey(map.get(entry.getKey()));
                break;
            default:
                NginxClojureRT.log.info(TAG + "Unhandled field : " + entry.getKey());
                break;
            }
        }
        return map;
    } else if (in.isJsonPrimitive()) {
        JsonPrimitive prim = in.getAsJsonPrimitive();
        if (prim.isBoolean()) {
            return prim.getAsBoolean();
        } else if (prim.isString()) {
            return prim.getAsString();
        } else if (prim.isNumber()) {
            Number num = prim.getAsNumber();
            // here you can handle double int/long values
            // and return any type you want
            // this solution will transform 3.0 float to long values
            if (Math.ceil(num.doubleValue()) == num.longValue()) {
                return num.longValue();
            } else {
                return num.doubleValue();
            }
        }
    }
    NginxClojureRT.log.info("Handling json null");
    return null;
}

From source file:com.canoo.dolphin.impl.codec.ValueEncoder.java

License:Apache License

static Object decodeValue(JsonElement jsonElement) {
    if (jsonElement == null || jsonElement.isJsonNull()) {
        return null;
    }/*from www  .  j a v  a 2 s  .  c o m*/
    if (!jsonElement.isJsonPrimitive()) {
        throw new JsonParseException("Illegal JSON detected");
    }
    final JsonPrimitive value = (JsonPrimitive) jsonElement;

    if (value.isString()) {
        return value.getAsString();
    } else if (value.isBoolean()) {
        return value.getAsBoolean();
    } else if (value.isNumber()) {
        return value.getAsNumber();
    }
    throw new JsonParseException("Currently only String, Boolean, or Number are allowed as primitives");
}

From source file:com.continusec.client.ObjectHash.java

License:Apache License

/**
 * Calculate the objecthash for a Gson JsonElement object, with a custom redaction prefix string.
 * @param o the Gson JsonElement to calculated the objecthash for.
 * @param r the string to use as a prefix to indicate that a string should be treated as a redacted subobject.
 * @return the objecthash for this object
 * @throws ContinusecException upon error
 */// w ww.  j  a  v  a 2  s .co  m
public static final byte[] objectHashWithRedaction(JsonElement o, String r) throws ContinusecException {
    if (o == null || o.isJsonNull()) {
        return hashNull();
    } else if (o.isJsonArray()) {
        return hashArray(o.getAsJsonArray(), r);
    } else if (o.isJsonObject()) {
        return hashObject(o.getAsJsonObject(), r);
    } else if (o.isJsonPrimitive()) {
        JsonPrimitive p = o.getAsJsonPrimitive();
        if (p.isBoolean()) {
            return hashBoolean(p.getAsBoolean());
        } else if (p.isNumber()) {
            return hashDouble(p.getAsDouble());
        } else if (p.isString()) {
            return hashString(p.getAsString(), r);
        } else {
            throw new InvalidObjectException();
        }
    } else {
        throw new InvalidObjectException();
    }
}

From source file:com.couchbase.plugin.basement.api.Client.java

License:Open Source License

private void addJsonElement(String key, JsonElement value, HashMap<String, Object> map) {

    if (value.isJsonArray()) {
        JsonArray jsonArray = value.getAsJsonArray();

        ArrayList listAsValue = new ArrayList<HashMap<String, Object>>();

        HashMap<String, Object> listElementMap = new HashMap<String, Object>();

        Iterator<JsonElement> jsonArrayIterator = jsonArray.iterator();
        while (jsonArrayIterator.hasNext()) {
            JsonElement jsonElement = jsonArrayIterator.next();

            listAsValue.add(parse(jsonElement.toString()));

        }//from w w  w  .  ja  v  a  2 s .  com

        map.put(key, listAsValue);

    } else if (value.isJsonPrimitive()) {
        // check the type using JsonPrimitive
        // TODO: check all types
        JsonPrimitive jsonPrimitive = value.getAsJsonPrimitive();
        if (jsonPrimitive.isNumber()) {
            map.put(key, jsonPrimitive.getAsInt());
        } else {
            map.put(key, jsonPrimitive.getAsString());
        }
    } else {
        map.put(key, parse(value.toString()));
    }

}

From source file:com.facebook.buck.json.RawParser.java

License:Apache License

/**
 * @return One of: String, Boolean, Long, Number, List<Object>, Map<String, Object>.
 *//*from ww w  .j a  va 2 s . co  m*/
@Nullable
@VisibleForTesting
static Object toRawTypes(JsonElement json) {
    // Cases are ordered from most common to least common.
    if (json.isJsonPrimitive()) {
        JsonPrimitive primitive = json.getAsJsonPrimitive();
        if (primitive.isString()) {
            return interner.intern(primitive.getAsString());
        } else if (primitive.isBoolean()) {
            return primitive.getAsBoolean();
        } else if (primitive.isNumber()) {
            Number number = primitive.getAsNumber();
            // Number is likely an instance of class com.google.gson.internal.LazilyParsedNumber.
            if (number.longValue() == number.doubleValue()) {
                return number.longValue();
            } else {
                return number;
            }
        } else {
            throw new IllegalStateException("Unknown primitive type: " + primitive);
        }
    } else if (json.isJsonArray()) {
        JsonArray array = json.getAsJsonArray();
        List<Object> out = Lists.newArrayListWithCapacity(array.size());
        for (JsonElement item : array) {
            out.add(toRawTypes(item));
        }
        return out;
    } else if (json.isJsonObject()) {
        Map<String, Object> out = new LinkedHashMap<>(json.getAsJsonObject().entrySet().size());
        for (Map.Entry<String, JsonElement> entry : json.getAsJsonObject().entrySet()) {
            // On a large project, without invoking intern(), we have seen `buck targets` OOM. When this
            // happened, according to the .hprof file generated using -XX:+HeapDumpOnOutOfMemoryError,
            // 39.6% of the memory was spent on char[] objects while 14.5% was spent on Strings.
            // (Another 10.5% was spent on java.util.HashMap$Entry.) Introducing intern() stopped the
            // OOM from happening.
            out.put(interner.intern(entry.getKey()), toRawTypes(entry.getValue()));
        }
        return out;
    } else if (json.isJsonNull()) {
        return null;
    } else {
        throw new IllegalStateException("Unknown type: " + json);
    }
}