Example usage for com.google.gson JsonPrimitive getAsNumber

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

Introduction

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

Prototype

@Override
public Number getAsNumber() 

Source Link

Document

convenience method to get this element as a Number.

Usage

From source file:org.locationtech.geogig.spring.service.LegacyMergeFeatureService.java

License:Open Source License

public RevFeature mergeFeatures(RepositoryProvider provider, String repoName, String request) {
    // get the repo
    Repository repository = getRepository(provider, repoName);
    if (repository != null) {
        final JsonParser parser = new JsonParser();
        final JsonElement conflictJson;
        try {/* w ww .ja  va 2  s  .com*/
            conflictJson = parser.parse(request);
        } catch (Exception e) {
            invalidPostData();
            return null;
        }

        if (conflictJson.isJsonObject()) {
            final JsonObject conflict = conflictJson.getAsJsonObject();
            String featureId = null;
            RevFeature ourFeature = null;
            RevFeatureType ourFeatureType = null;
            RevFeature theirFeature = null;
            RevFeatureType theirFeatureType = null;
            JsonObject merges = null;
            if (conflict.has("path") && conflict.get("path").isJsonPrimitive()) {
                featureId = conflict.get("path").getAsJsonPrimitive().getAsString();
            }
            if (featureId == null) {
                invalidPostData();
            }

            if (conflict.has("ours") && conflict.get("ours").isJsonPrimitive()) {
                String ourCommit = conflict.get("ours").getAsJsonPrimitive().getAsString();
                Optional<NodeRef> ourNode = parseID(ObjectId.valueOf(ourCommit), featureId, repository);
                if (ourNode.isPresent()) {
                    Optional<RevObject> object = repository.command(RevObjectParse.class)
                            .setObjectId(ourNode.get().getObjectId()).call();
                    Preconditions.checkState(object.isPresent() && object.get() instanceof RevFeature);

                    ourFeature = (RevFeature) object.get();

                    object = repository.command(RevObjectParse.class).setObjectId(ourNode.get().getMetadataId())
                            .call();
                    Preconditions.checkState(object.isPresent() && object.get() instanceof RevFeatureType);

                    ourFeatureType = (RevFeatureType) object.get();
                }
            } else {
                invalidPostData();
            }

            if (conflict.has("theirs") && conflict.get("theirs").isJsonPrimitive()) {
                String theirCommit = conflict.get("theirs").getAsJsonPrimitive().getAsString();
                Optional<NodeRef> theirNode = parseID(ObjectId.valueOf(theirCommit), featureId, repository);
                if (theirNode.isPresent()) {
                    Optional<RevObject> object = repository.command(RevObjectParse.class)
                            .setObjectId(theirNode.get().getObjectId()).call();
                    Preconditions.checkState(object.isPresent() && object.get() instanceof RevFeature);

                    theirFeature = (RevFeature) object.get();

                    object = repository.command(RevObjectParse.class)
                            .setObjectId(theirNode.get().getMetadataId()).call();
                    Preconditions.checkState(object.isPresent() && object.get() instanceof RevFeatureType);

                    theirFeatureType = (RevFeatureType) object.get();
                }
            } else {
                invalidPostData();
            }

            if (conflict.has("merges") && conflict.get("merges").isJsonObject()) {
                merges = conflict.get("merges").getAsJsonObject();
            }
            if (merges == null) {
                invalidPostData();
            }

            Preconditions.checkState(ourFeatureType != null || theirFeatureType != null);

            SimpleFeatureBuilder featureBuilder = new SimpleFeatureBuilder(
                    (SimpleFeatureType) (ourFeatureType != null ? ourFeatureType.type()
                            : theirFeatureType.type()));

            ImmutableList<PropertyDescriptor> descriptors = (ourFeatureType == null ? theirFeatureType
                    : ourFeatureType).descriptors();

            for (Map.Entry<String, JsonElement> entry : merges.entrySet()) {
                int descriptorIndex = getDescriptorIndex(entry.getKey(), descriptors);
                if (descriptorIndex != -1 && entry.getValue().isJsonObject()) {
                    PropertyDescriptor descriptor = descriptors.get(descriptorIndex);
                    JsonObject attributeObject = entry.getValue().getAsJsonObject();
                    if (attributeObject.has("ours") && attributeObject.get("ours").isJsonPrimitive()
                            && attributeObject.get("ours").getAsBoolean()) {
                        featureBuilder.set(descriptor.getName(),
                                ourFeature == null ? null : ourFeature.get(descriptorIndex).orNull());
                    } else if (attributeObject.has("theirs") && attributeObject.get("theirs").isJsonPrimitive()
                            && attributeObject.get("theirs").getAsBoolean()) {
                        featureBuilder.set(descriptor.getName(),
                                theirFeature == null ? null : theirFeature.get(descriptorIndex).orNull());
                    } else if (attributeObject.has("value") && attributeObject.get("value").isJsonPrimitive()) {
                        JsonPrimitive primitive = attributeObject.get("value").getAsJsonPrimitive();
                        if (primitive.isString()) {
                            try {
                                Object object = valueFromString(
                                        FieldType.forBinding(descriptor.getType().getBinding()),
                                        primitive.getAsString());
                                featureBuilder.set(descriptor.getName(), object);
                            } catch (Exception e) {
                                throw new CommandSpecException("Unable to convert attribute (" + entry.getKey()
                                        + ") to required type: " + descriptor.getType().getBinding().toString(),
                                        HttpStatus.INTERNAL_SERVER_ERROR);
                            }
                        } else if (primitive.isNumber()) {
                            try {
                                Object value = valueFromNumber(
                                        FieldType.forBinding(descriptor.getType().getBinding()),
                                        primitive.getAsNumber());
                                featureBuilder.set(descriptor.getName(), value);
                            } catch (Exception e) {
                                throw new CommandSpecException("Unable to convert attribute (" + entry.getKey()
                                        + ") to required type: " + descriptor.getType().getBinding().toString(),
                                        HttpStatus.INTERNAL_SERVER_ERROR);
                            }
                        } else if (primitive.isBoolean()) {
                            try {
                                Object value = valueFromBoolean(
                                        FieldType.forBinding(descriptor.getType().getBinding()),
                                        primitive.getAsBoolean());
                                featureBuilder.set(descriptor.getName(), value);
                            } catch (Exception e) {
                                throw new CommandSpecException("Unable to convert attribute (" + entry.getKey()
                                        + ") to required type: " + descriptor.getType().getBinding().toString(),
                                        HttpStatus.INTERNAL_SERVER_ERROR);
                            }
                        } else if (primitive.isJsonNull()) {
                            featureBuilder.set(descriptor.getName(), null);
                        } else {
                            throw new CommandSpecException(
                                    "Unsupported JSON type for attribute value (" + entry.getKey() + ")",
                                    HttpStatus.INTERNAL_SERVER_ERROR);
                        }
                    }
                }
            }
            SimpleFeature feature = featureBuilder.buildFeature(NodeRef.nodeFromPath(featureId));
            RevFeature revFeature = RevFeatureBuilder.build(feature);
            repository.objectDatabase().put(revFeature);

            return revFeature;
        } else {
            invalidPostData();
        }
    }
    return null;
}

From source file:org.mitre.jwt.model.ClaimSet.java

License:Apache License

/**
 * Set a primitive claim//from  w  w w  .j  a va  2s. co m
 */
public void setClaim(String key, JsonPrimitive prim) {
    invalidateString();
    if (prim == null) {
        // in case we get here with a primitive null
        claims.put(key, prim);
    } else if (prim.isBoolean()) {
        claims.put(key, prim.getAsBoolean());
    } else if (prim.isNumber()) {
        claims.put(key, prim.getAsNumber());
    } else if (prim.isString()) {
        claims.put(key, prim.getAsString());
    }

}

From source file:org.modelmapper.gson.JsonElementValueReader.java

License:Apache License

public Object get(JsonElement source, String memberName) {
    if (source.isJsonObject()) {
        JsonObject subjObj = source.getAsJsonObject();
        JsonElement propertyElement = subjObj.get(memberName);
        if (propertyElement == null)
            throw new IllegalArgumentException();

        if (propertyElement.isJsonObject())
            return propertyElement.getAsJsonObject();
        if (propertyElement.isJsonArray())
            return propertyElement.getAsJsonArray();
        if (propertyElement.isJsonPrimitive()) {
            JsonPrimitive jsonPrim = propertyElement.getAsJsonPrimitive();
            if (jsonPrim.isBoolean())
                return jsonPrim.getAsBoolean();
            if (jsonPrim.isNumber())
                return jsonPrim.getAsNumber();
            if (jsonPrim.isString())
                return jsonPrim.getAsString();
        }/*from  w  ww .j  a  v  a  2  s.c o  m*/
    }

    return null;
}

From source file:org.opendolphin.core.comm.JsonCodec.java

License:Apache License

private Object toValidValue(JsonElement jsonElement) {
    if (jsonElement.isJsonNull()) {
        return null;
    } else if (jsonElement.isJsonPrimitive()) {
        JsonPrimitive primitive = jsonElement.getAsJsonPrimitive();
        if (primitive.isBoolean()) {
            return primitive.getAsBoolean();
        } else if (primitive.isString()) {
            return primitive.getAsString();
        } else {/*from  www. ja  v  a2s .  co m*/
            return primitive.getAsNumber();
        }
    } else if (jsonElement.isJsonObject()) {
        JsonObject jsonObject = jsonElement.getAsJsonObject();
        if (jsonObject.has(Date.class.toString())) {
            try {
                return new SimpleDateFormat(ISO8601_FORMAT)
                        .parse(jsonObject.getAsJsonPrimitive(Date.class.toString()).getAsString());
            } catch (Exception e) {
                throw new RuntimeException("Can not converte!", e);
            }
        } else if (jsonObject.has(BigDecimal.class.toString())) {
            try {
                return new BigDecimal(jsonObject.getAsJsonPrimitive(BigDecimal.class.toString()).getAsString());
            } catch (Exception e) {
                throw new RuntimeException("Can not converte!", e);
            }
        } else if (jsonObject.has(Float.class.toString())) {
            try {
                return Float.valueOf(jsonObject.getAsJsonPrimitive(Float.class.toString()).getAsString());
            } catch (Exception e) {
                throw new RuntimeException("Can not converte!", e);
            }
        } else if (jsonObject.has(Double.class.toString())) {
            try {
                return Double.valueOf(jsonObject.getAsJsonPrimitive(Double.class.toString()).getAsString());
            } catch (Exception e) {
                throw new RuntimeException("Can not converte!", e);
            }
        }
    }
    throw new RuntimeException("Can not converte!");
}

From source file:org.openqa.selenium.json.JsonToBeanConverter.java

License:Apache License

@SuppressWarnings("unchecked")
private <T> T convert(Class<T> clazz, Object source, int depth) {
    if (source == null || source instanceof JsonNull) {
        return null;
    }/* w  ww. jav  a2s .co m*/

    if (source instanceof JsonElement) {
        JsonElement json = (JsonElement) source;

        if (json.isJsonPrimitive()) {
            JsonPrimitive jp = json.getAsJsonPrimitive();

            if (String.class.equals(clazz)) {
                return (T) jp.getAsString();
            }

            if (jp.isNumber()) {
                if (Integer.class.isAssignableFrom(clazz) || int.class.equals(clazz)) {
                    return (T) Integer.valueOf(jp.getAsNumber().intValue());
                } else if (Long.class.isAssignableFrom(clazz) || long.class.equals(clazz)) {
                    return (T) Long.valueOf(jp.getAsNumber().longValue());
                } else if (Float.class.isAssignableFrom(clazz) || float.class.equals(clazz)) {
                    return (T) Float.valueOf(jp.getAsNumber().floatValue());
                } else if (Double.class.isAssignableFrom(clazz) || double.class.equals(clazz)) {
                    return (T) Double.valueOf(jp.getAsNumber().doubleValue());
                } else {
                    return (T) convertJsonPrimitive(jp);
                }
            }
        }
    }

    if (isPrimitive(source.getClass())) {
        return (T) source;
    }

    if (isEnum(clazz, source)) {
        return (T) convertEnum(clazz, source);
    }

    if ("".equals(String.valueOf(source))) {
        return (T) source;
    }

    if (Command.class.equals(clazz)) {
        JsonObject json = new JsonParser().parse((String) source).getAsJsonObject();

        SessionId sessionId = null;
        if (json.has("sessionId") && !json.get("sessionId").isJsonNull()) {
            sessionId = convert(SessionId.class, json.get("sessionId"), depth + 1);
        }

        String name = json.get("name").getAsString();
        if (json.has("parameters")) {
            Map<String, ?> args = (Map<String, ?>) convert(HashMap.class, json.get("parameters"), depth + 1);
            return (T) new Command(sessionId, name, args);
        }

        return (T) new Command(sessionId, name);
    }

    if (Response.class.equals(clazz)) {
        Response response = new Response();
        JsonObject json = source instanceof JsonObject ? (JsonObject) source
                : new JsonParser().parse((String) source).getAsJsonObject();

        if (json.has("error") && !json.get("error").isJsonNull()) {
            String state = json.get("error").getAsString();
            response.setState(state);
            response.setStatus(errorCodes.toStatus(state, Optional.empty()));
            response.setValue(convert(Object.class, json.get("message")));
        }
        if (json.has("state") && !json.get("state").isJsonNull()) {
            String state = json.get("state").getAsString();
            response.setState(state);
            response.setStatus(errorCodes.toStatus(state, Optional.empty()));
        }
        if (json.has("status") && !json.get("status").isJsonNull()) {
            JsonElement status = json.get("status");
            if (status.getAsJsonPrimitive().isString()) {
                String state = status.getAsString();
                response.setState(state);
                response.setStatus(errorCodes.toStatus(state, Optional.empty()));
            } else {
                int intStatus = status.getAsInt();
                response.setState(errorCodes.toState(intStatus));
                response.setStatus(intStatus);
            }
        }
        if (json.has("sessionId") && !json.get("sessionId").isJsonNull()) {
            response.setSessionId(json.get("sessionId").getAsString());
        }

        if (json.has("value")) {
            response.setValue(convert(Object.class, json.get("value")));
        } else {
            response.setValue(convert(Object.class, json));
        }

        return (T) response;
    }

    if (SessionId.class.equals(clazz)) {
        // Stupid heuristic to tell if we are dealing with a selenium 2 or 3 session id.
        JsonElement json = source instanceof String ? new JsonParser().parse((String) source).getAsJsonObject()
                : (JsonElement) source;
        if (json.isJsonPrimitive()) {
            return (T) new SessionId(json.getAsString());
        }
        return (T) new SessionId(json.getAsJsonObject().get("value").getAsString());
    }

    if (Capabilities.class.isAssignableFrom(clazz)) {
        JsonObject json = source instanceof JsonElement ? ((JsonElement) source).getAsJsonObject()
                : new JsonParser().parse(source.toString()).getAsJsonObject();
        Map<String, Object> map = convertMap(json.getAsJsonObject(), depth);
        return (T) new MutableCapabilities(map);
    }

    if (Date.class.equals(clazz)) {
        return (T) new Date(Long.valueOf(String.valueOf(source)));
    }

    if (source instanceof String && !((String) source).startsWith("{") && Object.class.equals(clazz)) {
        return (T) source;
    }

    Method fromJson = getMethod(clazz, "fromJson");
    if (fromJson != null) {
        try {
            return (T) fromJson.invoke(null, source.toString());
        } catch (ReflectiveOperationException e) {
            throw new WebDriverException(e);
        }
    }

    if (depth == 0) {
        if (source instanceof String) {
            source = new JsonParser().parse((String) source);
        }
    }

    if (source instanceof JsonElement) {
        JsonElement element = (JsonElement) source;

        if (element.isJsonNull()) {
            return null;
        }

        if (element.isJsonPrimitive()) {
            return (T) convertJsonPrimitive(element.getAsJsonPrimitive());
        }

        if (element.isJsonArray()) {
            return (T) convertList(element.getAsJsonArray(), depth);
        }

        if (element.isJsonObject()) {
            if (Map.class.isAssignableFrom(clazz)) {
                return (T) convertMap(element.getAsJsonObject(), depth);
            }

            if (Object.class.equals(clazz)) {
                return (T) convertMap(element.getAsJsonObject(), depth);
            }

            return convertBean(clazz, element.getAsJsonObject(), depth);
        }
    }

    return (T) source; // Crap shoot here; probably a string.
}

From source file:org.openqa.selenium.remote.JsonToBeanConverter.java

License:Apache License

@SuppressWarnings("unchecked")
private <T> T convert(Class<T> clazz, Object source, int depth) {
    if (source == null || source instanceof JsonNull) {
        return null;
    }/*from  w w w.j a  v  a  2s.  c  o  m*/

    if (source instanceof JsonElement) {
        JsonElement json = (JsonElement) source;

        if (json.isJsonPrimitive()) {
            JsonPrimitive jp = json.getAsJsonPrimitive();

            if (String.class.equals(clazz)) {
                return (T) jp.getAsString();
            }

            if (jp.isNumber()) {
                if (Integer.class.isAssignableFrom(clazz) || int.class.equals(clazz)) {
                    return (T) Integer.valueOf(jp.getAsNumber().intValue());
                } else if (Long.class.isAssignableFrom(clazz) || long.class.equals(clazz)) {
                    return (T) Long.valueOf(jp.getAsNumber().longValue());
                } else if (Float.class.isAssignableFrom(clazz) || float.class.equals(clazz)) {
                    return (T) Float.valueOf(jp.getAsNumber().floatValue());
                } else if (Double.class.isAssignableFrom(clazz) || double.class.equals(clazz)) {
                    return (T) Double.valueOf(jp.getAsNumber().doubleValue());
                } else {
                    return (T) convertJsonPrimitive(jp);
                }
            }
        }
    }

    if (isPrimitive(source.getClass())) {
        return (T) source;
    }

    if (isEnum(clazz, source)) {
        return (T) convertEnum(clazz, source);
    }

    if ("".equals(String.valueOf(source))) {
        return (T) source;
    }

    if (Command.class.equals(clazz)) {
        JsonObject json = new JsonParser().parse((String) source).getAsJsonObject();

        SessionId sessionId = null;
        if (json.has("sessionId") && !json.get("sessionId").isJsonNull()) {
            sessionId = convert(SessionId.class, json.get("sessionId"), depth + 1);
        }

        String name = json.get("name").getAsString();
        if (json.has("parameters")) {
            Map<String, ?> args = (Map<String, ?>) convert(HashMap.class, json.get("parameters"), depth + 1);
            return (T) new Command(sessionId, name, args);
        }

        return (T) new Command(sessionId, name);
    }

    if (Response.class.equals(clazz)) {
        Response response = new Response();
        JsonObject json = source instanceof JsonObject ? (JsonObject) source
                : new JsonParser().parse((String) source).getAsJsonObject();

        if (json.has("error") && !json.get("error").isJsonNull()) {
            String state = json.get("error").getAsString();
            response.setState(state);
            response.setStatus(errorCodes.toStatus(state, Optional.empty()));
            response.setValue(convert(Object.class, json.get("message")));
        }
        if (json.has("state") && !json.get("state").isJsonNull()) {
            String state = json.get("state").getAsString();
            response.setState(state);
            response.setStatus(errorCodes.toStatus(state, Optional.empty()));
        }
        if (json.has("status") && !json.get("status").isJsonNull()) {
            JsonElement status = json.get("status");
            if (status.getAsJsonPrimitive().isString()) {
                String state = status.getAsString();
                response.setState(state);
                response.setStatus(errorCodes.toStatus(state, Optional.empty()));
            } else {
                int intStatus = status.getAsInt();
                response.setState(errorCodes.toState(intStatus));
                response.setStatus(intStatus);
            }
        }
        if (json.has("sessionId") && !json.get("sessionId").isJsonNull()) {
            response.setSessionId(json.get("sessionId").getAsString());
        }

        if (json.has("value")) {
            response.setValue(convert(Object.class, json.get("value")));
        } else {
            response.setValue(convert(Object.class, json));
        }

        return (T) response;
    }

    if (SessionId.class.equals(clazz)) {
        // Stupid heuristic to tell if we are dealing with a selenium 2 or 3 session id.
        JsonElement json = source instanceof String ? new JsonParser().parse((String) source).getAsJsonObject()
                : (JsonElement) source;
        if (json.isJsonPrimitive()) {
            return (T) new SessionId(json.getAsString());
        }
        return (T) new SessionId(json.getAsJsonObject().get("value").getAsString());
    }

    if (Capabilities.class.isAssignableFrom(clazz)) {
        JsonObject json = source instanceof JsonElement ? ((JsonElement) source).getAsJsonObject()
                : new JsonParser().parse(source.toString()).getAsJsonObject();
        Map<String, Object> map = convertMap(json.getAsJsonObject(), depth);
        return (T) new DesiredCapabilities(map);
    }

    if (Date.class.equals(clazz)) {
        return (T) new Date(Long.valueOf(String.valueOf(source)));
    }

    if (source instanceof String && !((String) source).startsWith("{") && Object.class.equals(clazz)) {
        return (T) source;
    }

    Method fromJson = getMethod(clazz, "fromJson");
    if (fromJson != null) {
        try {
            return (T) fromJson.invoke(null, source.toString());
        } catch (IllegalArgumentException e) {
            throw new WebDriverException(e);
        } catch (IllegalAccessException e) {
            throw new WebDriverException(e);
        } catch (InvocationTargetException e) {
            throw new WebDriverException(e);
        }
    }

    if (depth == 0) {
        if (source instanceof String) {
            source = new JsonParser().parse((String) source);
        }
    }

    if (source instanceof JsonElement) {
        JsonElement element = (JsonElement) source;

        if (element.isJsonNull()) {
            return null;
        }

        if (element.isJsonPrimitive()) {
            return (T) convertJsonPrimitive(element.getAsJsonPrimitive());
        }

        if (element.isJsonArray()) {
            return (T) convertList(element.getAsJsonArray(), depth);
        }

        if (element.isJsonObject()) {
            if (Map.class.isAssignableFrom(clazz)) {
                return (T) convertMap(element.getAsJsonObject(), depth);
            }

            if (Object.class.equals(clazz)) {
                return (T) convertMap(element.getAsJsonObject(), depth);
            }

            return convertBean(clazz, element.getAsJsonObject(), depth);
        }
    }

    return (T) source; // Crap shoot here; probably a string.
}

From source file:org.plos.crepo.model.metadata.RepoMetadata.java

License:Open Source License

/**
 * Special case for parsing numbers from JSON.
 * <p/>//from  w  ww .j ava2 s. co  m
 * This is used instead of {@link JsonPrimitive#getAsNumber}, which may return a {@link
 * com.google.gson.internal.LazilyParsedNumber}. The problem with LazilyParsedNumber is that it doesn't belong to one
 * of the familiar Number subtypes (e.g., Integer, Double, Long), so its {@link Object#equals} and {@link
 * Object#hashCode} don't behave intuitively.
 * <p/>
 * Our imperfect solution is to use {@link Number#doubleValue()}, to be consistent with how Gson produces numbers
 * nested in arrays and objects. That is:
 * <pre>
 *   new Gson().fromJson("[0]", List.class).get(0).getClass() // is Double
 * </pre>
 * Compare to:
 * <pre>
 *   new Gson().fromJson("0", Number.class).getClass() // is LazilyParsedNumber
 * </pre>
 * This ensures that numbers parsed from JSON can be compared consistently with {@link Object#equals}, whether they
 * were formatted as integers or decimals. The client should treat such objects as abstract Numbers and, if they
 * require a particular subtype (such as Integer), call the appropriate method (such as {@link Number#intValue}).
 *
 * @param jsonPrimitive a primitive JSON number
 * @return a Java-native Number object of equivalent value
 */
private static Number asNumber(JsonPrimitive jsonPrimitive) {
    return jsonPrimitive.getAsNumber().doubleValue();
}

From source file:org.qcert.runtime.DataComparator.java

License:Apache License

private static DType getType(JsonElement obj) {
    if (obj == null) {
        return DType.DT_JNULL;
    } else if (obj.isJsonNull()) {
        return DType.DT_NULL;
    } else if (obj.isJsonPrimitive()) {
        final JsonPrimitive prim = obj.getAsJsonPrimitive();
        if (prim.isBoolean()) {
            return DType.DT_BOOL;
        } else if (prim.isString()) {
            return DType.DT_STRING;
        } else if (prim.isNumber()) {
            final Number num = prim.getAsNumber();
            if (num instanceof LazilyParsedNumber) {
                return DType.DT_LAZYNUM;
            } else if (num instanceof Long || num instanceof Short || num instanceof Integer) {
                return DType.DT_LONG;
            } else if (num instanceof Double || num instanceof Short || num instanceof Float) {
                return DType.DT_DOUBLE;
            } else {
                throw new RuntimeException(
                        "Unknown primitive json number type: " + num + " of type " + num.getClass());
            }/*from  w w w  .  j a  v  a  2s  .  c o m*/
        } else {
            throw new RuntimeException("Unknown primitive json type: " + prim);
        }
    } else if (obj.isJsonArray()) {
        return DType.DT_COLL;
    } else if (obj.isJsonObject()) {
        return DType.DT_REC;
    } else {
        throw new RuntimeException("Unknown json type: " + obj + " of type " + obj.getClass());
    }
}

From source file:org.spongepowered.common.util.persistence.JsonTranslator.java

License:MIT License

private static Object convert(JsonElement element) {
    if (element.isJsonObject()) {
        MemoryDataView container = new MemoryDataContainer();
        for (Entry<String, JsonElement> entry : ((JsonObject) element).entrySet()) {
            Object value = convert(entry.getValue());
            if (value != null) {
                container.set(DataQuery.of(entry.getKey()), value);
            }/*from   ww w.j a  va  2s .c om*/
        }
        return container;
    } else if (element.isJsonArray()) {
        return Lists.newArrayList(Iterables.transform((JsonArray) element, JsonTranslator::convert));
    } else if (element.isJsonPrimitive()) {
        JsonPrimitive primitive = (JsonPrimitive) element;
        if (primitive.isString()) {
            return primitive.getAsString();
        } else if (primitive.isBoolean()) {
            return primitive.getAsBoolean();
        } else if (primitive.isNumber()) {
            return primitive.getAsNumber();
        }
    }
    return null;
}

From source file:org.springframework.data.cloudant.core.UnmappedDataAdapter.java

License:Apache License

@Override
public T deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {
    Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ")
            .registerTypeAdapter(DateTime.class, new DateTimeDataAdapter()).create();
    T doc = gson.fromJson(json, typeOfT);
    Map<String, Object> unmapped = new HashMap<>();
    List<String> nameList = getNestedField(doc.getClass());
    JsonObject object = json.getAsJsonObject();

    //add support for annotated fields ...hack for now
    nameList.add("_id");
    nameList.add("_rev");
    nameList.add("doc_type");
    for (Map.Entry<String, JsonElement> entry : object.entrySet()) {
        if (!nameList.contains(entry.getKey())) {
            if (entry.getValue().isJsonArray()) {
                unmapped.put(entry.getKey(), entry.getValue().getAsJsonArray());
            } else if (entry.getValue().isJsonObject()) {
                unmapped.put(entry.getKey(), entry.getValue().getAsJsonObject());
            } else if (entry.getValue().isJsonPrimitive()) {
                JsonPrimitive v = entry.getValue().getAsJsonPrimitive();
                if (v.isBoolean()) {
                    unmapped.put(entry.getKey(), v.getAsBoolean());
                } else if (v.isNumber()) {
                    unmapped.put(entry.getKey(), v.getAsNumber());
                } else if (v.isString()) {
                    unmapped.put(entry.getKey(), v.getAsString());
                } else if (v.isJsonNull()) {
                    unmapped.put(entry.getKey(), null);
                }//ww w  .j a  v a2  s.co m
            } else if (entry.getValue().isJsonNull()) {
                unmapped.put(entry.getKey(), null);
            } else {
                unmapped.put(entry.getKey(), entry.getValue().getAsString());
            }
        }

    }
    doc.setUnmappedFields(unmapped);
    return doc;
}