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:com.ryanantkowiak.jOptionsHouseAPI.JsonUtilities.java

License:Open Source License

/**
 * Recursively print the contents of a GSON JSON element.
 * /*from  w  w  w.  ja  v a  2 s  .c  o m*/
 * @param element   the GSON JSON element to be printed
 * @param prefix   output will be prefixed with this string
 */
public static void printJson(JsonElement element, String prefix) {
    if (null == prefix || prefix.isEmpty()) {
        prefix = "";
    }

    if (null == element || element.isJsonNull()) {
        System.out.println(prefix + " [null]");
        return;
    }

    else if (element.isJsonPrimitive()) {
        JsonPrimitive p = element.getAsJsonPrimitive();
        if (p.isBoolean()) {
            System.out.println(prefix + " [bool=" + p.getAsBoolean() + "]");
        } else if (p.isString()) {
            System.out.println(prefix + " [string='" + p.getAsString() + "']");
        } else if (p.isNumber()) {
            System.out.println(prefix + " [number=" + p.getAsDouble() + "]");
        }
    }

    else if (element.isJsonArray()) {
        System.out.println(prefix + " [array]");
        for (int i = 0; i < element.getAsJsonArray().size(); ++i) {
            String newPrefix = prefix + "[" + i + "]";
            printJson(element.getAsJsonArray().get(i), newPrefix);
        }
    }

    else if (element.isJsonObject()) {
        JsonObject obj = element.getAsJsonObject();

        for (Map.Entry<String, JsonElement> entry : obj.entrySet()) {
            String key = entry.getKey();
            JsonElement value = entry.getValue();
            String newPrefix = prefix + "." + key;
            printJson(value, newPrefix);
        }
    }

}

From source file:com.seleritycorp.common.base.config.ConfigUtils.java

License:Apache License

/**
 * Adds a JSON primitive to a Config.//from ww w  . j  a v a2s. com
 * 
 * @param primitive The primitive to add
 * @param config The config instance to add the primitive to
 * @param key The key in the config space
 */
private static void loadJson(JsonPrimitive primitive, ConfigImpl config, String key) {
    String value = null;
    if (primitive.isBoolean()) {
        boolean bool = primitive.getAsBoolean();
        value = bool ? "true" : "false";
    } else if (primitive.isString()) {
        value = primitive.getAsString();
    } else if (primitive.isNumber()) {
        value = Double.toString(primitive.getAsDouble());
    }
    config.set(key, value);
}

From source file:com.softwarementors.extjs.djn.router.processor.standard.json.JsonRequestProcessor.java

License:Open Source License

private @CheckForNull Object toSimpleJavaType(JsonElement jsonValue) {
    if (jsonValue == null)
        return null; //VR
    Object value = null;//from www .j  a  va  2s .c om
    if (!jsonValue.isJsonNull()) {
        if (jsonValue.isJsonPrimitive()) {
            JsonPrimitive primitive = jsonValue.getAsJsonPrimitive();
            if (primitive.isBoolean()) {
                value = Boolean.valueOf(primitive.getAsBoolean());
            } else if (primitive.isNumber()) {
                value = Double.valueOf(primitive.getAsDouble());
            } else if (primitive.isString()) {
                value = primitive.getAsString();
            } else {
                throw UnexpectedException.forUnexpectedCodeBranchExecuted();
            }
        } else if (jsonValue.isJsonArray()) {
            //This simply does not work (?) 
            JsonArray array = jsonValue.getAsJsonArray();
            Object[] result = new Object[array.size()];
            for (int i = 0; i < array.size(); i++) {
                result[i] = toSimpleJavaType(array.get(i));
            }
            value = result;
        } else if (jsonValue.isJsonObject()) {
            //This simply does not work (?)
            //value = getGson().fromJson(jsonValue, Map.class );

            JsonObject obj = jsonValue.getAsJsonObject();
            Iterator<Entry<String, JsonElement>> properties = obj.entrySet().iterator();
            Map<String, Object> result = new HashMap<String, Object>();
            while (properties.hasNext()) {
                Entry<String, JsonElement> property = properties.next();
                JsonElement propertyValue = property.getValue();
                result.put(property.getKey(), toSimpleJavaType(propertyValue));
            }
            value = result;
        } else {
            throw UnexpectedException.forUnexpectedCodeBranchExecuted();
        }
    }

    return value;
}

From source file:com.softwarementors.extjs.djn.test.config.GsonBuilderConfiguratorForTesting.java

License:Open Source License

private static int getIntValue(JsonObject parent, String elementName) {
    assert parent != null;
    assert !StringUtils.isEmpty(elementName);

    JsonElement element = parent.get(elementName);
    if (!element.isJsonPrimitive()) {
        throw new JsonParseException("Element + '" + elementName + "' must be a valid integer");
    }/*  w  ww . j a  v  a2 s.co  m*/
    JsonPrimitive primitiveElement = (JsonPrimitive) element;
    if (!primitiveElement.isNumber()) {
        throw new JsonParseException("Element + '" + elementName + "' must be a valid integer");
    }
    return primitiveElement.getAsInt();
}

From source file:com.synflow.cx.internal.instantiation.properties.Specializer.java

License:Open Source License

/**
 * Returns an IR expression from the given JSON element.
 * /*ww  w.  j  a v  a2s  .  co  m*/
 * @param json
 *            a JSON element (should be a primitive)
 * @return an expression, or <code>null</code>
 */
public Expression transformJson(JsonElement json) {
    if (json.isJsonPrimitive()) {
        JsonPrimitive primitive = json.getAsJsonPrimitive();
        if (primitive.isBoolean()) {
            return eINSTANCE.createExprBool(primitive.getAsBoolean());
        } else if (primitive.isNumber()) {
            return eINSTANCE.createExprInt(primitive.getAsBigInteger());
        } else if (primitive.isString()) {
            return eINSTANCE.createExprString(primitive.getAsString());
        }
    }
    return null;
}

From source file:com.talvish.tales.auth.jwt.TokenManager.java

License:Apache License

/**
 * Helper method that takes a string segment (e.g. headers, claims) and 
 * base64 decodes, parses out the json and generates a map of the values. 
 * @param theSegment the segment to process
 * @return the map of values generated from the segment
 *//* w ww.j  a v  a 2s.  com*/
private Map<String, Object> processSegment(String theSegment, int theSegmentIndex) {
    Map<String, Object> outputItems = new HashMap<>();
    ClaimDetails claimDetails;
    String claimName = null;
    JsonElement claimValue = null;

    try {
        JsonObject inputJson = (JsonObject) jsonParser
                .parse(new String(base64Decoder.decode(theSegment), utf8));
        for (Entry<String, JsonElement> entry : inputJson.entrySet()) {
            claimName = entry.getKey();
            claimValue = entry.getValue();
            claimDetails = this.claimHandlers.get(claimName);
            if (claimDetails != null) {
                outputItems.put(claimName,
                        claimDetails.getTypeAdapter().getFromFormatTranslator().translate(claimValue));
            } else if (claimValue.isJsonPrimitive()) {
                JsonPrimitive primitiveJson = (JsonPrimitive) claimValue;
                if (primitiveJson.isString()) {
                    outputItems.put(claimName, primitiveJson.getAsString());
                } else if (primitiveJson.isNumber()) {
                    outputItems.put(claimName, primitiveJson.getAsNumber());
                } else if (primitiveJson.isBoolean()) {
                    outputItems.put(claimName, primitiveJson.getAsBoolean());
                } else {
                    throw new IllegalArgumentException(String.format(
                            "Claim '%s' is a primitive json type with value '%s', which has no mechanism for translation.",
                            claimName, claimValue.getAsString()));
                }
            } else {
                throw new IllegalArgumentException(String.format(
                        "Claim '%s' is not a primitive json type with value '%s', which has no mechanism for translation.",
                        claimName, claimValue.getAsString()));
            }
        }
    } catch (JsonParseException e) {
        throw new IllegalArgumentException(
                String.format("Segment '%d' contains invalid json.", theSegmentIndex), e);
    } catch (TranslationException e) {
        // claim name will be set if we have this exception, if not it will be null and will not cause a problem
        // but to be safe for the value, which should also be not null, we check so no exceptions are thrown
        if (claimValue != null) {
            throw new IllegalArgumentException(
                    String.format("Claim '%s' in segment '%d' contains invalid data '%s'.", claimName,
                            theSegmentIndex, claimValue.getAsString()),
                    e);
        } else {
            throw new IllegalArgumentException(String.format(
                    "Claim '%s' in segment '%d' contains invalid data.", claimName, theSegmentIndex), e);
        }
    }
    return outputItems;
}

From source file:com.tsc9526.monalisa.tools.json.MelpJson.java

License:Open Source License

public static Object primitive(JsonPrimitive e) {
    if (e.isNumber()) {
        Number n = e.getAsNumber();
        if (n instanceof LazilyParsedNumber) {
            LazilyParsedNumber ln = (LazilyParsedNumber) n;
            String value = ln.toString();
            if (value.indexOf('.') >= 0) {
                return ln.doubleValue();
            } else {
                return ln.longValue();
            }//from   w  w w  . ja v  a  2s  .c o  m
        } else {
            return n;
        }
    } else if (e.isBoolean()) {
        return e.getAsBoolean();
    } else {
        return e.getAsString();
    }
}

From source file:com.vmware.xenon.common.serialization.ObjectCollectionTypeConverter.java

License:Open Source License

@Override
public Collection<Object> deserialize(JsonElement json, Type type, JsonDeserializationContext context)
        throws JsonParseException {

    if (!json.isJsonArray()) {
        throw new JsonParseException("Expecting a json array object but found: " + json);
    }//from  w  ww.  ja va  2 s .  c  o m

    Collection<Object> result;
    if (TYPE_SET.equals(type)) {
        result = new HashSet<>();
    } else if (TYPE_LIST.equals(type) || TYPE_COLLECTION.equals(type)) {
        result = new LinkedList<>();
    } else {
        throw new JsonParseException("Unexpected target type: " + type);
    }

    JsonArray jsonArray = json.getAsJsonArray();
    for (JsonElement entry : jsonArray) {
        if (entry.isJsonNull()) {
            result.add(null);
        } else if (entry.isJsonPrimitive()) {
            JsonPrimitive elem = entry.getAsJsonPrimitive();
            Object value = null;
            if (elem.isBoolean()) {
                value = elem.getAsBoolean();
            } else if (elem.isString()) {
                value = elem.getAsString();
            } else if (elem.isNumber()) {
                // We don't know if this is an integer, long, float or double...
                BigDecimal num = elem.getAsBigDecimal();
                try {
                    value = num.longValueExact();
                } catch (ArithmeticException e) {
                    value = num.doubleValue();
                }
            } else {
                throw new RuntimeException("Unexpected value type for json element:" + elem);
            }
            result.add(value);
        } else {
            // keep JsonElement to prevent stringified json issues
            result.add(entry);
        }
    }
    return result;
}

From source file:com.voxelplugineering.voxelsniper.service.persistence.JsonDataSource.java

License:Open Source License

/**
 * Recursively converts the given {@link JsonElement} to a
 * {@link DataContainer}.//  w ww  .j a  v a  2s .  c om
 * 
 * @param rootelement The element to convert
 * @return The new {@link DataContainer}
 */
public DataContainer toContainer(JsonElement rootelement) {
    DataContainer container = new MemoryContainer("");

    if (rootelement.isJsonObject()) {
        JsonObject root = rootelement.getAsJsonObject();
        for (Entry<String, JsonElement> entry : root.entrySet()) {
            String key = entry.getKey();
            JsonElement element = entry.getValue();
            if (element.isJsonPrimitive()) {
                JsonPrimitive primitive = element.getAsJsonPrimitive();
                if (primitive.isBoolean()) {
                    container.writeBoolean(key, primitive.getAsBoolean());
                } else if (primitive.isString()) {
                    container.writeString(key, primitive.getAsString());
                } else if (primitive.isNumber()) {
                    container.writeNumber(key, primitive.getAsNumber());
                }
            } else if (element.isJsonObject()) {
                container.writeContainer(key, toContainer(element));
            }
        }
    }

    return container;

}

From source file:com.voxelplugineering.voxelsniper.service.persistence.JsonDataSourceReader.java

License:Open Source License

/**
 * Recursively converts the given {@link JsonElement} to a {@link DataContainer}.
 * //www  . ja v a2 s . c o m
 * @param rootelement The element to convert
 * @return The new {@link DataContainer}
 */
public DataContainer toContainer(JsonElement rootelement) {
    DataContainer container = new MemoryContainer("");

    if (rootelement.isJsonObject()) {
        JsonObject root = rootelement.getAsJsonObject();
        for (Entry<String, JsonElement> entry : root.entrySet()) {
            String key = entry.getKey();
            JsonElement element = entry.getValue();
            if (element.isJsonPrimitive()) {
                JsonPrimitive primitive = element.getAsJsonPrimitive();
                if (primitive.isBoolean()) {
                    container.setBoolean(key, primitive.getAsBoolean());
                } else if (primitive.isString()) {
                    container.setString(key, primitive.getAsString());
                } else if (primitive.isNumber()) {
                    container.setNumber(key, primitive.getAsNumber());
                }
            } else if (element.isJsonObject()) {
                container.setContainer(key, toContainer(element));
            }
        }
    }

    return container;

}