Example usage for com.google.gson JsonPrimitive getAsBoolean

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

Introduction

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

Prototype

@Override
public boolean getAsBoolean() 

Source Link

Document

convenience method to get this element as a boolean value.

Usage

From source file:angularBeans.remote.InvocationHandler.java

License:LGPL

private void update(Object o, JsonObject params) {

    if (params != null) {

        // boolean firstIn = false;

        for (Map.Entry<String, JsonElement> entry : params.entrySet()) {

            JsonElement value = entry.getValue();
            String name = entry.getKey();

            if ((name.equals("sessionUID")) || (name.equals("args"))) {
                continue;
            }/*from ww  w  . j  a v a2  s  .c o m*/

            if ((value.isJsonObject()) && (!value.isJsonNull())) {

                String getName;
                try {
                    getName = CommonUtils.obtainGetter(o.getClass().getDeclaredField(name));

                    Method getter = o.getClass().getMethod(getName);

                    Object subObj = getter.invoke(o);

                    // logger.log(Level.INFO, "#entring sub object "+name);
                    update(subObj, value.getAsJsonObject());

                } catch (NoSuchFieldException | SecurityException | IllegalAccessException
                        | IllegalArgumentException | InvocationTargetException | NoSuchMethodException e) {

                    e.printStackTrace();
                }

            }
            // ------------------------------------
            if (value.isJsonArray()) {

                try {
                    String getter = CommonUtils.obtainGetter(o.getClass().getDeclaredField(name));

                    Method get = o.getClass().getDeclaredMethod(getter);

                    Type type = get.getGenericReturnType();
                    ParameterizedType pt = (ParameterizedType) type;
                    Type actType = pt.getActualTypeArguments()[0];

                    String className = actType.toString();

                    className = className.substring(className.indexOf("class") + 6);
                    Class clazz = Class.forName(className);

                    JsonArray array = value.getAsJsonArray();

                    Collection collection = (Collection) get.invoke(o);
                    Object elem;
                    for (JsonElement element : array) {
                        if (element.isJsonPrimitive()) {
                            JsonPrimitive primitive = element.getAsJsonPrimitive();

                            elem = element;
                            if (primitive.isBoolean())
                                elem = primitive.getAsBoolean();
                            if (primitive.isString()) {
                                elem = primitive.getAsString();
                            }
                            if (primitive.isNumber())
                                elem = primitive.isNumber();

                        } else {

                            elem = util.deserialise(clazz, element);
                        }

                        try {

                            if (collection instanceof List) {

                                if (collection.contains(elem))
                                    collection.remove(elem);
                            }

                            collection.add(elem);
                        } catch (UnsupportedOperationException e) {
                            Logger.getLogger("AngularBeans").log(java.util.logging.Level.WARNING,
                                    "trying to modify an immutable collection : " + name);
                        }

                    }

                } catch (Exception e) {
                    e.printStackTrace();

                }

            }

            // ------------------------------------------
            if (value.isJsonPrimitive() && (!name.equals("setSessionUID"))) {
                try {

                    if (!CommonUtils.hasSetter(o.getClass(), name)) {
                        continue;
                    }
                    name = "set" + name.substring(0, 1).toUpperCase() + name.substring(1);

                    Class type = null;
                    for (Method set : o.getClass().getDeclaredMethods()) {
                        if (CommonUtils.isSetter(set)) {
                            if (set.getName().equals(name)) {
                                Class<?>[] pType = set.getParameterTypes();

                                type = pType[0];
                                break;

                            }
                        }

                    }

                    if (type.equals(LobWrapper.class))
                        continue;

                    Object param = null;
                    if ((params.entrySet().size() >= 1) && (type != null)) {

                        param = CommonUtils.convertFromString(value.getAsString(), type);

                    }

                    o.getClass().getMethod(name, type).invoke(o, param);

                } catch (Exception e) {
                    e.printStackTrace();

                }
            }

        }
    }

}

From source file:at.ac.tuwien.infosys.jcloudscale.datastore.mapping.type.json.JsonBooleanTypeAdapter.java

License:Apache License

@Override
public Boolean deserialize(JsonElement element, TypeMetadata<JsonElement> typeMetadata) {
    JsonPrimitive jsonPrimitive = (JsonPrimitive) element;
    if (!jsonPrimitive.isBoolean()) {
        throw new DatastoreException("Invalid value for boolean type.");
    }/*from ww w  .jav  a  2s .c  om*/
    return jsonPrimitive.getAsBoolean();
}

From source file:ccm.pay2spawn.util.JsonNBTHelper.java

License:Open Source License

/**
 * There is no way to detect number types and NBT is picky about this. Lets hope the original type id is there, otherwise we are royally screwed.
 *//*from w w  w .  j av  a2s .co m*/
public static NBTBase parseJSON(JsonPrimitive element) {
    String string = element.getAsString();
    if (string.contains(":")) {
        for (int id = 0; id < NBTTypes.length; id++) {
            if (string.startsWith(NBTTypes[id] + ":")) {
                String value = string.replace(NBTTypes[id] + ":", "");
                value = RandomRegistry.solveRandom(id, value);
                switch (id) {
                // 0 = END
                case BYTE:
                    return new NBTTagByte(Byte.parseByte(value));
                case SHORT:
                    return new NBTTagShort(Short.parseShort(value));
                case INT:
                    return new NBTTagInt(Integer.parseInt(value));
                case LONG:
                    return new NBTTagLong(Long.parseLong(value));
                case FLOAT:
                    return new NBTTagFloat(Float.parseFloat(value));
                case DOUBLE:
                    return new NBTTagDouble(Double.parseDouble(value));
                case BYTE_ARRAY:
                    return parseJSONByteArray(value);
                case STRING:
                    return new NBTTagString(value);
                // 9 = LIST != JsonPrimitive
                // 10 = COMPOUND != JsonPrimitive
                case INT_ARRAY:
                    return parseJSONIntArray(value);
                }
            }
        }
    }

    // Now it becomes guesswork.
    if (element.isString())
        return new NBTTagString(string);
    if (element.isBoolean())
        return new NBTTagByte((byte) (element.getAsBoolean() ? 1 : 0));

    Number n = element.getAsNumber();
    if (n instanceof Byte)
        return new NBTTagByte(n.byteValue());
    if (n instanceof Short)
        return new NBTTagShort(n.shortValue());
    if (n instanceof Integer)
        return new NBTTagInt(n.intValue());
    if (n instanceof Long)
        return new NBTTagLong(n.longValue());
    if (n instanceof Float)
        return new NBTTagFloat(n.floatValue());
    if (n instanceof Double)
        return new NBTTagDouble(n.doubleValue());

    throw new NumberFormatException(element.toString() + " is was not able to be parsed.");
}

From source file:ccm.pay2spawn.util.JsonNBTHelper.java

License:Open Source License

public static JsonPrimitive fixNulls(JsonPrimitive primitive) {
    if (primitive.isBoolean())
        return new JsonPrimitive(primitive.getAsBoolean());
    if (primitive.isNumber())
        return new JsonPrimitive(primitive.getAsNumber());
    if (primitive.isString())
        return new JsonPrimitive(primitive.getAsString());
    return JSON_PARSER.parse(primitive.toString()).getAsJsonPrimitive();
}

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 ww .j a  v 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.adobe.acs.commons.remoteassets.impl.RemoteAssetsNodeSyncImpl.java

License:Apache License

/**
 * Set a simple resource property from the fetched JSON.
 *
 * @param value Object/*from w  w w.j  a  v a  2s .c  om*/
 * @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   w ww.  j  av  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));
        }// ww  w . j  ava2  s .co  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;
    }/* www . ja va 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.cloudbase.CBNaturalDeserializer.java

License:Open Source License

private Object handlePrimitive(JsonPrimitive json) {
    if (json.isBoolean())
        return json.getAsBoolean();
    else if (json.isString())
        return json.getAsString();
    else {//from w  ww. j a  v a2s.c  o  m
        BigDecimal bigDec = json.getAsBigDecimal();
        // Find out if it is an int type
        try {
            bigDec.toBigIntegerExact();
            try {
                return bigDec.intValueExact();
            } catch (ArithmeticException e) {
            }
            return bigDec.longValue();
        } catch (ArithmeticException e) {
        }
        // Just return it as a double
        return bigDec.doubleValue();
    }
}