Example usage for com.google.gson JsonElement isJsonNull

List of usage examples for com.google.gson JsonElement isJsonNull

Introduction

In this page you can find the example usage for com.google.gson JsonElement isJsonNull.

Prototype

public boolean isJsonNull() 

Source Link

Document

provides check for verifying if this element represents a null value or not.

Usage

From source file:lolxmpp.api.RiotAPI.java

License:Open Source License

public JsonObject makeRequest(String apiPath) throws APIException {
    String apiHost = region.apiHost();
    String tryUrl = "https://" + apiHost + apiPath;
    try {/*from  w  w w  .  j  ava  2s  . c o  m*/
        URL url = new URL(tryUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestProperty("X-Riot-Token", key);

        if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
            throw new APIException("[RAPI] Request Failed. HTTP Error Code: " + connection.getResponseCode()
                    + ", URL: " + tryUrl + ", KEY:" + key);
        }

        JsonElement element = new JsonParser()
                .parse(new JsonReader(new InputStreamReader(connection.getInputStream())));
        if (!element.isJsonNull()) {
            return element.getAsJsonObject();
        }
    } catch (MalformedURLException e) {
        System.err.println("[RAPI] Something's wrong!");
        System.err.println("[RAPI] Malformed URL: " + tryUrl);
        e.printStackTrace();
    } catch (IOException e) {
        System.err.println("[RAPI] Something's wrong!");
        System.err.println("[RAPI] IOException");
        e.printStackTrace();
    }

    return new JsonObject();
}

From source file:me.drakeet.multitype.sample.weibo.WeiboContentDeserializer.java

License:Apache License

private @NonNull String stringOrEmpty(JsonElement jsonElement) {
    return jsonElement.isJsonNull() ? "" : jsonElement.getAsString();
}

From source file:melnorme.lang.utils.gson.GsonHelper.java

License:Open Source License

public boolean isPresent(JsonObject jsonObject, String key) {
    JsonElement jsonElement = jsonObject.get(key);
    return jsonElement != null && !jsonElement.isJsonNull();
}

From source file:net.boreeas.riotapi.com.riotgames.platform.broadcast.BroadcastNotification.java

License:Apache License

public void readExternal(ObjectInput in) throws IOException {
    byte[] buffer = new byte[in.readInt()];
    int i = 0;/*from w  w  w . java  2 s .  com*/
    while (i < buffer.length - 1) {
        i += in.read(buffer, i, buffer.length - i);
    }
    String json = new String(buffer, "UTF-8");
    JsonElement elem = new JsonParser().parse(json);
    this.json = elem == null || elem.isJsonNull() ? null : elem.getAsJsonObject();
}

From source file:net.caseif.flint.common.util.agent.rollback.CommonRollbackAgent.java

License:Open Source License

@Override
public void initializeStateStore() {
    try {/*from  w  w w  .ja v a  2s .  c o  m*/
        if (!stateStore.exists()) {
            //noinspection ResultOfMethodCallIgnored
            stateStore.createNewFile();
        }
        JsonElement json = new JsonParser().parse(new FileReader(stateStore));
        if (json.isJsonNull()) {
            json = new JsonObject();
        }
        json.getAsJsonObject().add(getArena().getId(), new JsonObject());
        saveState(json.getAsJsonObject());
    } catch (IOException ex) {
        throw new RuntimeException("Failed to intialize state store for arena " + arena.getId(), ex);
    }
}

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  w ww . j a  v a 2s  . 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.inervo.WMFWiki11.java

License:Open Source License

protected boolean isEmptyOrNull(JsonElement element) {
    if (element == null || element.isJsonNull()) {
        return false;
    }//w  w  w.j  a v a  2s.  c  o m

    String str = element.getAsString();
    if (str.length() == 0 || str.contentEquals("0")) {
        return false;
    }

    return true;
}

From source file:net.minecraftforge.common.crafting.CraftingHelper.java

License:Open Source License

@Nonnull
public static Ingredient getIngredient(JsonElement json, JsonContext context) {
    if (json == null || json.isJsonNull())
        throw new JsonSyntaxException("Json cannot be null");
    if (context == null)
        throw new IllegalArgumentException("getIngredient Context cannot be null");

    if (json.isJsonArray()) {
        List<Ingredient> ingredients = Lists.newArrayList();
        List<Ingredient> vanilla = Lists.newArrayList();
        json.getAsJsonArray().forEach((ele) -> {
            Ingredient ing = CraftingHelper.getIngredient(ele, context);

            if (ing.getClass() == Ingredient.class) {
                //Vanilla, Due to how we read it splits each itemstack, so we pull out to re-merge later
                vanilla.add(ing);//from www .j a  v  a2  s.co m
            } else {
                ingredients.add(ing);
            }
        });

        if (!vanilla.isEmpty()) {
            ingredients.add(Ingredient.merge(vanilla));
        }

        if (ingredients.size() == 0)
            throw new JsonSyntaxException("Item array cannot be empty, at least one item must be defined");

        if (ingredients.size() == 1)
            return ingredients.get(0);

        return new CompoundIngredient(ingredients);
    }

    if (!json.isJsonObject())
        throw new JsonSyntaxException("Expcted ingredient to be a object or array of objects");

    JsonObject obj = (JsonObject) json;

    String type = context.appendModId(JsonUtils.getString(obj, "type", "minecraft:item"));
    if (type.isEmpty())
        throw new JsonSyntaxException("Ingredient type can not be an empty string");

    if (type.equals("minecraft:item")) {
        String item = JsonUtils.getString(obj, "item");
        if (item.startsWith("#")) {
            Ingredient constant = context.getConstant(item.substring(1));
            if (constant == null)
                throw new JsonSyntaxException("Ingredient referenced invalid constant: " + item);
            return constant;
        }
    }

    IIngredientFactory factory = ingredients.get(new ResourceLocation(type));
    if (factory == null)
        throw new JsonSyntaxException("Unknown ingredient type: " + type);

    return factory.parse(context, obj);
}

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);/* www  .j  a va2 s .  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.servicestack.client.Utils.java

License:Open Source License

private static String getAsStringOrNull(JsonElement jsonElement) {
    return jsonElement.isJsonNull() ? null : jsonElement.getAsString();
}