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:net.daporkchop.toobeetooteebot.text.JsonUtils.java

License:Open Source License

/**
 * Gets a human-readable description of the given JsonElement's type.  For example: "a number (4)"
 *///from www. ja  va2s  .  c o m
public static String toString(JsonElement json) {
    String s = org.apache.commons.lang3.StringUtils.abbreviateMiddle(String.valueOf(json), "...", 10);

    if (json == null) {
        return "null (missing)";
    } else if (json.isJsonNull()) {
        return "null (json)";
    } else if (json.isJsonArray()) {
        return "an array (" + s + ")";
    } else if (json.isJsonObject()) {
        return "an object (" + s + ")";
    } else {
        if (json.isJsonPrimitive()) {
            JsonPrimitive jsonprimitive = json.getAsJsonPrimitive();

            if (jsonprimitive.isNumber()) {
                return "a number (" + s + ")";
            }

            if (jsonprimitive.isBoolean()) {
                return "a boolean (" + s + ")";
            }
        }

        return s;
    }
}

From source file:net.doubledoordev.backend.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 JSONPARSER.parse(primitive.toString()).getAsJsonPrimitive();
}

From source file:net.nexustools.njs.JSON.java

License:Open Source License

public JSON(final Global global) {
    super(global);
    setHidden("stringify", new AbstractFunction(global) {

        public java.lang.String stringify(BaseObject object) {
            StringBuilder builder = new StringBuilder();
            stringify(object, builder);/*w  w w  . ja  v  a  2s.c o  m*/
            return builder.toString();
        }

        public void stringify(BaseObject object, StringBuilder builder) {
            if (Utilities.isUndefined(object)) {
                builder.append("null");
                return;
            }

            BaseObject toJSON = object.get("toJSON", OR_NULL);
            if (toJSON != null)
                stringify0(((BaseFunction) toJSON).call(object), builder);
            else
                stringify0(object, builder);
        }

        public void stringify0(BaseObject object, StringBuilder builder) {
            if (object instanceof GenericArray) {
                builder.append('[');
                if (((GenericArray) object).length() > 0) {
                    stringify(object.get(0), builder);
                    for (int i = 1; i < ((GenericArray) object).length(); i++) {
                        builder.append(',');
                        stringify(object.get(i), builder);
                    }
                }
                builder.append(']');
            } else if (object instanceof String.Instance) {
                builder.append('"');
                builder.append(object.toString());
                builder.append('"');
            } else if (object instanceof Number.Instance) {
                double number = ((Number.Instance) object).value;
                if (Double.isNaN(number) || Double.isInfinite(number))
                    builder.append("null");

                builder.append(object.toString());
            } else if (object instanceof Boolean.Instance)
                builder.append(object.toString());
            else {
                builder.append('{');
                Iterator<java.lang.String> it = object.keys().iterator();
                if (it.hasNext()) {

                    java.lang.String key = it.next();
                    builder.append('"');
                    builder.append(key);
                    builder.append("\":");
                    stringify(object.get(key), builder);

                    if (it.hasNext()) {
                        do {
                            builder.append(',');
                            key = it.next();
                            builder.append('"');
                            builder.append(key);
                            builder.append("\":");
                            stringify(object.get(key), builder);
                        } while (it.hasNext());
                    }
                }
                builder.append('}');
            }
        }

        @Override
        public BaseObject call(BaseObject _this, BaseObject... params) {
            switch (params.length) {
            case 0:
                return Undefined.INSTANCE;

            case 1:
                if (params[0] == Undefined.INSTANCE)
                    return Undefined.INSTANCE;
                return global.wrap(stringify(params[0]));

            default:
                return global.wrap("undefined");
            }
        }

        @Override
        public java.lang.String name() {
            return "JSON_stringify";
        }
    });
    setHidden("parse", new AbstractFunction(global) {
        final Gson GSON;
        {
            GsonBuilder gsonBuilder = new GsonBuilder();
            gsonBuilder.registerTypeAdapter(BaseObject.class, new JsonDeserializer<BaseObject>() {
                @Override
                public BaseObject deserialize(JsonElement je, Type type, JsonDeserializationContext jdc)
                        throws JsonParseException {
                    if (je.isJsonNull())
                        return Null.INSTANCE;
                    if (je.isJsonPrimitive()) {
                        JsonPrimitive primitive = je.getAsJsonPrimitive();
                        if (primitive.isBoolean())
                            return primitive.getAsBoolean() ? global.Boolean.TRUE : global.Boolean.FALSE;
                        if (primitive.isNumber())
                            return global.wrap(primitive.getAsDouble());
                        if (primitive.isString())
                            return global.wrap(primitive.getAsString());
                        throw new UnsupportedOperationException(primitive.toString());
                    }
                    if (je.isJsonObject()) {
                        GenericObject go = new GenericObject(global);
                        JsonObject jo = je.getAsJsonObject();
                        for (Map.Entry<java.lang.String, JsonElement> entry : jo.entrySet()) {
                            go.set(entry.getKey(), deserialize(entry.getValue(), type, jdc));
                        }
                        return go;
                    }
                    if (je.isJsonArray()) {
                        JsonArray ja = je.getAsJsonArray();
                        BaseObject[] array = new BaseObject[ja.size()];
                        for (int i = 0; i < array.length; i++) {
                            array[i] = deserialize(ja.get(i), type, jdc);
                        }
                        return new GenericArray(global, array);
                    }
                    throw new UnsupportedOperationException(je.toString());
                }
            });
            GSON = gsonBuilder.create();
        }

        @Override
        public BaseObject call(BaseObject _this, BaseObject... params) {
            try {
                return GSON.fromJson(params[0].toString(), BaseObject.class);
            } catch (com.google.gson.JsonSyntaxException ex) {
                throw new Error.JavaException("SyntaxError", "Unexpected token", ex);
            }
        }

        @Override
        public java.lang.String name() {
            return "JSON_parse";
        }
    });
}

From source file:net.oauth.jsontoken.JsonToken.java

License:Apache License

private Long getParamAsLong(String param) {
    JsonPrimitive primitive = getParamAsPrimitive(param);
    if (primitive != null && (primitive.isNumber() || primitive.isString())) {
        try {//from www. ja v  a 2 s  .c o m
            return primitive.getAsLong();
        } catch (NumberFormatException e) {
            return null;
        }
    }
    return null;
}

From source file:net.praqma.tracey.tracey_rabbitmq_neo4j_bridge.Tracey2Neo.java

private Object getPrimitiveType(JsonElement jo) {
    if (!jo.isJsonPrimitive()) {
        return null;
    }/*from w  ww  .j  a v  a  2  s .  co m*/
    JsonPrimitive jp = jo.getAsJsonPrimitive();
    if (jp.isBoolean()) {
        return jp.getAsBoolean();
    }
    if (jp.isNumber()) {
        return jp.getAsNumber();
    }
    if (jp.isString()) {
        return jp.getAsString();
    }
    return null;
}

From source file:org.apache.abdera2.activities.io.gson.BaseAdapter.java

License:Apache License

public ASBase deserialize(JsonElement el, Type type, JsonDeserializationContext context)
        throws JsonParseException {
    JsonObject obj = (JsonObject) el;//from   www. j a  v  a  2 s .  co  m
    ASBase.Builder<?, ?> builder;
    if (type == Collection.class)
        builder = Collection.makeCollection();
    else if (type == Activity.class)
        builder = Activity.makeActivity();
    else if (type == MediaLink.class)
        builder = MediaLink.makeMediaLink();
    else if (type == PlaceObject.class)
        builder = PlaceObject.makePlace();
    else if (type == Mood.class)
        builder = Mood.makeMood();
    else if (type == Address.class)
        builder = Address.makeAddress();
    else {
        JsonPrimitive ot = obj.getAsJsonPrimitive("objectType");
        if (ot != null) {
            String ots = ot.getAsString();
            Class<? extends ASObject.Builder> _class = objsmap.get(ots);
            if (_class != null) {
                builder = Discover.locate(_class, _class.getName());
                try {
                    builder = _class.getConstructor(String.class).newInstance(ots);
                } catch (Throwable t) {
                }

            } else
                builder = ASObject.makeObject(ots);
        } else {
            if (obj.has("verb") && (obj.has("actor") || obj.has("object") || obj.has("target"))) {
                builder = Activity.makeActivity();
            } else if (obj.has("items")) {
                builder = Collection.makeCollection();
            } else {
                builder = ASObject.makeObject(); // anonymous
            }
        }
    }
    for (Entry<String, JsonElement> entry : obj.entrySet()) {
        String name = entry.getKey();
        if (name.equalsIgnoreCase("objectType"))
            continue;
        Class<?> _class = map.get(name);
        JsonElement val = entry.getValue();
        if (val.isJsonPrimitive()) {
            if (_class != null) {
                builder.set(name, context.deserialize(val, _class));
            } else {
                JsonPrimitive prim = val.getAsJsonPrimitive();
                if (prim.isBoolean())
                    builder.set(name, prim.getAsBoolean());
                else if (prim.isNumber())
                    builder.set(name, prim.getAsNumber());
                else {
                    builder.set(name, prim.getAsString());
                }
            }
        } else if (val.isJsonArray()) {
            ImmutableList.Builder<Object> list = ImmutableList.builder();
            JsonArray arr = val.getAsJsonArray();
            processArray(arr, _class, context, list);
            builder.set(name, list.build());
        } else if (val.isJsonObject()) {
            if (map.containsKey(name)) {
                builder.set(name, context.deserialize(val, map.get(name)));
            } else
                builder.set(name, context.deserialize(val, ASObject.class));
        }
    }
    return builder.get();
}

From source file:org.apache.abdera2.activities.io.gson.BaseAdapter.java

License:Apache License

private void processArray(JsonArray arr, Class<?> _class, JsonDeserializationContext context,
        ImmutableList.Builder<Object> list) {
    for (JsonElement mem : arr) {
        if (mem.isJsonPrimitive()) {
            if (_class != null) {
                list.add(context.deserialize(mem, _class));
            } else {
                JsonPrimitive prim2 = (JsonPrimitive) mem;
                if (prim2.isBoolean())
                    list.add(prim2.getAsBoolean());
                else if (prim2.isNumber())
                    list.add(prim2.getAsNumber());
                else
                    list.add(prim2.getAsString());
            }// w  w  w . j av a  2  s  .c  o  m
        } else if (mem.isJsonObject()) {
            list.add(context.deserialize(mem, _class != null ? _class : ASObject.class));
        } else if (mem.isJsonArray()) {
            JsonArray array = mem.getAsJsonArray();
            ImmutableList.Builder<Object> objs = ImmutableList.builder();
            processArray(array, _class, context, objs);
            list.add(objs.build());
        }
    }
}

From source file:org.apache.abdera2.activities.io.gson.MultimapAdapter.java

License:Apache License

protected static Object primdes(JsonPrimitive prim) {
    if (prim.isBoolean())
        return prim.getAsBoolean();
    else if (prim.isNumber())
        return prim.getAsNumber();
    else//from  ww w .  j  a va  2 s .c  o m
        return prim.getAsString();
}

From source file:org.apache.airavata.common.utils.JSONUtil.java

License:Apache License

private static boolean isEqual(JsonPrimitive primitiveOrig, JsonPrimitive primitiveNew) {
    if (primitiveOrig == null && primitiveNew == null) {
        return true;
    } else if (primitiveOrig == null || primitiveNew == null) {
        return false;
    } else {//from   w  w  w.ja v  a2  s. c o  m
        if (primitiveOrig.isString() && primitiveNew.isString()) {
            if (!primitiveOrig.getAsString().equals(primitiveNew.getAsString())) {
                return false;
            }
        } else if (primitiveOrig.isBoolean() && primitiveNew.isBoolean()) {
            if ((Boolean.valueOf(primitiveOrig.getAsBoolean()).compareTo(primitiveNew.getAsBoolean()) != 0)) {
                return false;
            }
        } else if (primitiveOrig.isNumber() && primitiveNew.isNumber()) {
            if (new Double(primitiveOrig.getAsDouble()).compareTo(primitiveNew.getAsDouble()) != 0) {
                return false;
            }
        } else {
            return primitiveOrig.isJsonNull() && primitiveNew.isJsonNull();
        }
    }
    return true;
}

From source file:org.apache.hadoop.hive.json.JsonSchemaFinder.java

License:Apache License

private static HiveType pickType(JsonElement json) {
    if (json.isJsonPrimitive()) {
        JsonPrimitive prim = (JsonPrimitive) json;
        if (prim.isBoolean()) {
            return new BooleanType();
        } else if (prim.isNumber()) {
            BigDecimal dec = prim.getAsBigDecimal();
            if (dec.scale() > 0) {
                return new FloatingPointType(dec.doubleValue());
            } else {
                return new IntegerType(dec.longValue());
            }//from w  w  w.ja v a 2s.  c  om
        } else {
            String str = prim.getAsString();
            if (DATE_PATTERN.matcher(str).matches()) {
                return new TimestampType();
            } else if (HEX_PATTERN.matcher(str).matches()) {
                return new BinaryType();
            } else {
                return new StringType();
            }
        }
    } else if (json.isJsonNull()) {
        return new NullType();
    } else if (json.isJsonArray()) {
        ListType result = new ListType();
        for (JsonElement child : ((JsonArray) json)) {
            HiveType sub = pickType(child);
            if (result.elementType == null) {
                result.elementType = sub;
            } else {
                result.elementType = mergeType(result.elementType, sub);
            }
        }
        return result;
    } else {
        JsonObject obj = (JsonObject) json;
        StructType result = new StructType();
        for (Map.Entry<String, JsonElement> field : obj.entrySet()) {
            String fieldName = field.getKey();
            HiveType type = pickType(field.getValue());
            result.fields.put(fieldName, type);
        }
        StringBuilder builder = new StringBuilder();
        boolean first = true;
        for (String key : result.fields.keySet()) {
            if (first) {
                first = false;
            } else {
                builder.append(",");
            }
            builder.append(key);
        }
        result.values.add(builder.toString());
        return result;
    }
}