Example usage for com.google.gson JsonPrimitive isBoolean

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

Introduction

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

Prototype

public boolean isBoolean() 

Source Link

Document

Check whether this primitive contains a boolean value.

Usage

From source file:me.boomboompower.togglechat.utils.BetterJsonObject.java

License:Open Source License

/**
 * The optional boolean method, returns the default value if
 * the key is null, empty or the data does not contain
 * the key. This will also return the default value if
 * the data value is not a boolean/*from  w w  w  .  ja  v a 2s  . c o  m*/
 *
 * @param key the key the value will be loaded from
 * @return the value in the json data set or the default if the key cannot be found
 */
public boolean optBoolean(String key, boolean value) {
    if (key == null || key.isEmpty() || !has(key)) {
        return value;
    }

    JsonPrimitive primitive = asPrimitive(get(key));

    if (primitive != null && primitive.isBoolean()) {
        return primitive.getAsBoolean();
    }
    return value;
}

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)"
 *//*  w  w w  .  java 2  s. co 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

/**
 * 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 www.  ja  va  2s .c om*/
public static Tag parseJSON(JsonPrimitive element) {
    String string = element.getAsString();
    if (string.contains(":")) {
        String[] split = string.split(":", 2);
        switch (TagType.getByTypeName(split[0])) {
        case TAG_END:
            return new EndTag();
        case TAG_BYTE:
            return new ByteTag("", Byte.parseByte(split[1]));
        case TAG_SHORT:
            return new ShortTag("", Short.parseShort(split[1]));
        case TAG_INT:
            return new IntTag("", Integer.parseInt(split[1]));
        case TAG_LONG:
            return new LongTag("", Long.parseLong(split[1]));
        case TAG_FLOAT:
            return new FloatTag("", Float.parseFloat(split[1]));
        case TAG_DOUBLE:
            return new DoubleTag("", Double.parseDouble(split[1]));
        case TAG_BYTE_ARRAY:
            return parseJSONByteArray(split[1]);
        case TAG_STRING:
            return new StringTag("", split[1]);
        // TAG_LIST != JsonPrimitive
        // TAG_COMPOUND != JsonPrimitive
        case TAG_INT_ARRAY:
            return parseJSONIntArray(split[1]);
        case TAG_SHORT_ARRAY:
            return parseJSONShortArray(split[1]);
        }
    }

    // Now it becomes guesswork.
    if (element.isString())
        return new StringTag("", string);
    if (element.isBoolean())
        return new ByteTag("", element.getAsBoolean());

    Number n = element.getAsNumber();
    if (n instanceof Byte)
        return new ByteTag("", n.byteValue());
    if (n instanceof Short)
        return new ShortTag("", n.shortValue());
    if (n instanceof Integer)
        return new IntTag("", n.intValue());
    if (n instanceof Long)
        return new LongTag("", n.longValue());
    if (n instanceof Float)
        return new FloatTag("", n.floatValue());
    if (n instanceof Double)
        return new DoubleTag("", n.doubleValue());

    try {
        return new IntTag("", Integer.parseInt(element.toString()));
    } catch (NumberFormatException ignored) {

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

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);//from  w  ww . j a  v  a 2  s  .  com
            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.praqma.tracey.tracey_rabbitmq_neo4j_bridge.Tracey2Neo.java

private Object getPrimitiveType(JsonElement jo) {
    if (!jo.isJsonPrimitive()) {
        return null;
    }/*w w  w.  j a  va  2s .  c o  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 w ww  .  j a  v  a  2s.c  o  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  ww. j  av  a  2s . co 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   www . ja v a2 s  .  c om
        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  . j ava  2 s  . co  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;
}