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:org.gogoup.dddutils.misc.CodingHelper.java

License:Apache License

public static Object getObjectFromJson(JsonPrimitive value) {
    if (value.isString()) {
        return value.getAsString();
    } else if (value.isBoolean()) {
        return value.getAsBoolean();
    } else if (value.isNumber()) {
        return value.getAsNumber();
    } else if (value.isJsonNull()) {
        return null;
    } else if (value.isJsonArray()) {
        JsonArray objArray = value.getAsJsonArray();
        Object[] values = new Object[objArray.size()];
        for (int i = 0; i < values.length; i++) {
            values[i] = getObjectFromJson(objArray.get(i).getAsJsonPrimitive());
        }//from  www  .j  a v a2  s .  co m
        return values;
    } else {
        throw new IllegalArgumentException("value");
    }
}

From source file:org.helios.dashkuj.core.apiimpl.AbstractDashku.java

License:Open Source License

/**
 * Builds a post body in post body format to send the dirty fields for the passed domain object.
 * The field values are URL encoded. /*from w w w  . j av  a 2s. c  om*/
 * @param domainObject the domain object to generate the diff post for
 * @return the diff post body
 */
protected Buffer buildDirtyUpdatePost(AbstractDashkuDomainObject domainObject) {
    StringBuilder b = new StringBuilder();
    JsonObject jsonDomainObject = GsonFactory.getInstance().newNoSerGson().toJsonTree(domainObject)
            .getAsJsonObject();
    Set<String> fieldnames = domainObject.getDirtyFieldNames();
    if (fieldnames.isEmpty())
        return null;
    for (String dirtyFieldName : domainObject.getDirtyFieldNames()) {
        try {
            JsonPrimitive jp = jsonDomainObject.getAsJsonPrimitive(dirtyFieldName);
            String value = null;
            if (jp.isString()) {
                value = URLEncoder.encode(jp.getAsString(), "UTF-8");
            } else if (jp.isNumber()) {
                value = "" + jp.getAsNumber();
            } else if (jp.isBoolean()) {
                value = "" + jp.getAsBoolean();
            } else {
                value = jp.toString();
            }
            b.append(dirtyFieldName).append("=").append(value).append("&");
        } catch (Exception ex) {
            throw new RuntimeException("Failed to encode dirty field [" + dirtyFieldName + "]", ex);
        }
    }
    b.deleteCharAt(b.length() - 1);
    try {
        String encoded = b.toString(); //URLEncoder.encode(b.toString(), "UTF-8");
        log.info("Update Post:[\n\t{}\n]", encoded);
        return new Buffer(encoded);
    } catch (Exception e) {
        throw new RuntimeException(e); // ain't happening
    }
}

From source file:org.hibernate.search.elasticsearch.query.impl.JsonDrivenProjection.java

License:LGPL

@Override
public Object convertHit(JsonObject hit, ConversionContext conversionContext) {
    JsonElement value = extractFieldValue(hit.get("_source").getAsJsonObject(), absoluteName);
    if (value == null || value.isJsonNull()) {
        return null;
    }/*from w ww . ja va  2s  .  co  m*/

    // TODO: HSEARCH-2255 should we do it?
    if (!value.isJsonPrimitive()) {
        throw LOG.unsupportedProjectionOfNonJsonPrimitiveFields(value);
    }

    JsonPrimitive primitive = value.getAsJsonPrimitive();

    if (primitive.isBoolean()) {
        return primitive.getAsBoolean();
    } else if (primitive.isNumber()) {
        // TODO HSEARCH-2255 this will expose a Gson-specific Number implementation; Can we somehow return an Integer,
        // Long... etc. instead?
        return primitive.getAsNumber();
    } else if (primitive.isString()) {
        return primitive.getAsString();
    } else {
        // TODO HSEARCH-2255 Better raise an exception?
        return primitive.toString();
    }
}

From source file:org.hibernate.search.elasticsearch.query.impl.TwoWayFieldBridgeProjection.java

License:LGPL

public void addDocumentFieldsRecursively(Document tmp, JsonElement value, String fieldName) {
    if (value == null || value.isJsonNull()) {
        return;/*from  ww  w  .j  a  va2  s  .  co  m*/
    }

    PrimitiveProjection configuredProjection = primitiveProjections.get(fieldName);
    if (configuredProjection != null) {
        // Those projections are handled separately, see the calling method
        return;
    }

    if (value.isJsonObject()) {
        JsonObject jsonObject = value.getAsJsonObject();
        for (Map.Entry<String, JsonElement> entry : jsonObject.entrySet()) {
            String nestedFieldName = fieldName + "." + entry.getKey();
            JsonElement nestedFieldValue = entry.getValue();
            addDocumentFieldsRecursively(tmp, nestedFieldValue, nestedFieldName);
        }
    } else if (value.isJsonArray()) {
        JsonArray jsonArray = value.getAsJsonArray();
        for (JsonElement nestedValue : jsonArray) {
            addDocumentFieldsRecursively(tmp, nestedValue, fieldName);
        }
    } else {
        JsonPrimitive primitive = value.getAsJsonPrimitive();

        if (primitive.isBoolean()) {
            tmp.add(new StringField(fieldName, String.valueOf(primitive.getAsBoolean()), Store.NO));
        } else if (primitive.isNumber()) {
            tmp.add(new DoubleField(fieldName, primitive.getAsDouble(), Store.NO));
        } else if (primitive.isString()) {
            tmp.add(new StringField(fieldName, primitive.getAsString(), Store.NO));
        } else {
            // TODO HSEARCH-2255 Better raise an exception?
            tmp.add(new StringField(fieldName, primitive.getAsString(), Store.NO));
        }
    }
}

From source file:org.hillview.storage.JsonFileLoader.java

License:Open Source License

void append(IAppendableColumn[] columns, JsonElement e) {
    if (!e.isJsonObject())
        this.error("JSON array element is not a JsonObject");
    JsonObject obj = e.getAsJsonObject();
    for (IAppendableColumn col : columns) {
        JsonElement el = obj.get(col.getName());
        if (el == null || el.isJsonNull()) {
            col.appendMissing();//from   w w w. j  av  a2 s.co  m
            continue;
        }

        if (!el.isJsonPrimitive())
            this.error("JSON array element is a non-primitive field");
        JsonPrimitive prim = el.getAsJsonPrimitive();

        if (prim.isBoolean()) {
            col.append(prim.getAsBoolean() ? "true" : "false");
        } else if (prim.isNumber()) {
            col.append(prim.getAsDouble());
        } else if (prim.isString()) {
            col.parseAndAppendString(prim.getAsString());
        } else {
            this.error("Unexpected Json value" + prim.toString());
        }
    }
}

From source file:org.i3xx.step.uno.impl.util.GsonHashMapDeserializer.java

License:Apache License

private Object handlePrimitive(JsonPrimitive json) {
    if (json.isBoolean())
        return json.getAsBoolean();
    else if (json.isString())
        return json.getAsString();
    else {/*from   w  w w  .  ja  v a 2  s .c om*/
        //System.out.println("GND handlePrimitive: "+json.getAsString());
        BigDecimal bigDec = json.getAsBigDecimal();
        if (json.getAsString().indexOf('.') == -1) {
            // Find out if it is an int type
            try {
                //System.out.println("GND: "+bigDec.toPlainString());
                /*
                bigDec.toBigIntegerExact();
                try { 
                   return bigDec.intValueExact(); }
                catch(ArithmeticException e) {}
                */
                return bigDec.longValue();
            } catch (ArithmeticException e) {
            }
        }
        // Just return it as a double
        return bigDec.doubleValue();
    }
}

From source file:org.immutables.mongo.fixture.holder.HolderJsonSerializer.java

License:Apache License

@Override
public Holder deserialize(JsonElement json, Type type, JsonDeserializationContext context)
        throws JsonParseException {
    JsonObject root = (JsonObject) json;

    ImmutableHolder.Builder builder = ImmutableHolder.builder();

    if (root.has("id")) {
        builder.id(root.get("id").getAsString());
    }/*from  ww w  .j ava  2  s  . c o m*/

    JsonElement value = root.get(VALUE_PROPERTY);
    if (value == null) {
        throw new JsonParseException(String.format("%s not found for %s in JSON", VALUE_PROPERTY, type));
    }

    if (value.isJsonObject()) {
        final String valueTypeName = value.getAsJsonObject().get(Holder.TYPE_PROPERTY).getAsString();
        try {
            Class<?> valueType = Class.forName(valueTypeName);
            builder.value(context.deserialize(value, valueType));
        } catch (ClassNotFoundException e) {
            throw new JsonParseException(
                    String.format("Couldn't construct value class %s for %s", valueTypeName, type), e);
        }
    } else if (value.isJsonPrimitive()) {
        final JsonPrimitive primitive = value.getAsJsonPrimitive();
        if (primitive.isString()) {
            builder.value(primitive.getAsString());
        } else if (primitive.isNumber()) {
            builder.value(primitive.getAsInt());
        } else if (primitive.isBoolean()) {
            builder.value(primitive.getAsBoolean());
        }
    } else {
        throw new JsonParseException(String.format("Couldn't deserialize %s : %s. Not a primitive or object",
                VALUE_PROPERTY, value));
    }

    return builder.build();

}

From source file:org.ireas.intuition.IntuitionLoader.java

License:Open Source License

private Optional<JsonObject> getDomainObject(final JsonElement element) {
    Optional<JsonObject> domainObject = Optional.absent();

    // two types of valid responses:
    // (1) {"messages": {"<domain>": {  } } }
    // --> messages found
    // (2) {"messages": {"<domain>": false} }
    // --> no messages available

    if (!element.isJsonObject()) {
        throw new IllegalArgumentException();
    }/*from   ww  w.  j  a  va  2s . c om*/
    JsonObject rootObject = element.getAsJsonObject();
    if (!rootObject.has(KEY_MESSAGES)) {
        throw new IllegalArgumentException();
    }
    JsonElement messagesElement = rootObject.get(KEY_MESSAGES);
    if (!messagesElement.isJsonObject()) {
        throw new IllegalArgumentException();
    }
    JsonObject messagesObject = messagesElement.getAsJsonObject();
    if (!messagesObject.has(domain)) {
        throw new IllegalArgumentException();
    }
    JsonElement domainElement = messagesObject.get(domain);

    if (domainElement.isJsonObject()) {
        // valid response (1): messages found
        domainObject = Optional.of(domainElement.getAsJsonObject());
    } else if (domainElement.isJsonPrimitive()) {
        JsonPrimitive domainPrimitive = domainElement.getAsJsonPrimitive();
        if (!domainPrimitive.isBoolean()) {
            throw new IllegalArgumentException();
        }
        boolean domainBoolean = domainPrimitive.getAsBoolean();
        if (domainBoolean) {
            throw new IllegalArgumentException();
        }
        // valid response (2): no messages available
    } else {
        throw new IllegalArgumentException();
    }

    return domainObject;
}

From source file:org.jboss.aerogear.android.impl.datamanager.SQLStore.java

License:Apache License

private void saveElement(JsonObject serialized, String path, Serializable id) {
    String sql = String.format(
            "insert into %s_property (PROPERTY_NAME, PROPERTY_VALUE, PARENT_ID) values (?,?,?)", className);
    Set<Entry<String, JsonElement>> members = serialized.entrySet();
    String pathVar = path.isEmpty() ? "" : ".";
    for (Entry<String, JsonElement> member : members) {
        JsonElement jsonValue = member.getValue();
        String propertyName = member.getKey();
        if (jsonValue.isJsonObject()) {
            saveElement((JsonObject) jsonValue, path + pathVar + propertyName, id);
        } else {/*from ww  w  . jav  a2 s  .  c  om*/
            if (jsonValue.isJsonPrimitive()) {
                JsonPrimitive primitive = jsonValue.getAsJsonPrimitive();
                if (primitive.isBoolean()) {
                    Integer value = primitive.getAsBoolean() ? 1 : 0;
                    database.execSQL(sql, new Object[] { path + pathVar + propertyName, value, id });
                } else if (primitive.isNumber()) {
                    Number value = primitive.getAsNumber();
                    database.execSQL(sql, new Object[] { path + pathVar + propertyName, value, id });
                } else if (primitive.isString()) {
                    String value = primitive.getAsString();
                    database.execSQL(sql, new Object[] { path + pathVar + propertyName, value, id });
                } else {
                    throw new IllegalArgumentException(jsonValue + " isn't a number, boolean, or string");
                }

            } else {
                throw new IllegalArgumentException(jsonValue + " isn't a JsonPrimitive");
            }

        }
    }
}

From source file:org.jboss.aerogear.android.impl.datamanager.SQLStore.java

License:Apache License

private void buildKeyValuePairs(JsonObject where, List<Pair<String, String>> keyValues, String parentPath) {
    Set<Entry<String, JsonElement>> keys = where.entrySet();
    String pathVar = parentPath.isEmpty() ? "" : ".";//Set a dot if parent path is not empty
    for (Entry<String, JsonElement> entry : keys) {
        String key = entry.getKey();
        String path = parentPath + pathVar + key;
        JsonElement jsonValue = entry.getValue();
        if (jsonValue.isJsonObject()) {
            buildKeyValuePairs((JsonObject) jsonValue, keyValues, path);
        } else {/*from   w ww .j  a  v a  2s  . c  om*/
            if (jsonValue.isJsonPrimitive()) {
                JsonPrimitive primitive = jsonValue.getAsJsonPrimitive();
                if (primitive.isBoolean()) {
                    Integer value = primitive.getAsBoolean() ? 1 : 0;
                    keyValues.add(new Pair<String, String>(path, value.toString()));
                } else if (primitive.isNumber()) {
                    Number value = primitive.getAsNumber();
                    keyValues.add(new Pair<String, String>(path, value.toString()));
                } else if (primitive.isString()) {
                    String value = primitive.getAsString();
                    keyValues.add(new Pair<String, String>(path, value));
                } else {
                    throw new IllegalArgumentException(jsonValue + " isn't a number, boolean, or string");
                }

            } else {
                throw new IllegalArgumentException(jsonValue + " isn't a JsonPrimitive");
            }

        }
    }
}