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:com.softwarementors.extjs.djn.router.processor.standard.json.JsonRequestProcessor.java

License:Open Source License

@CheckForNull
private static JsonObject getMethodParametersJsonOptions(JsonObject object) {
    assert object != null;

    JsonElement options = object.get(JsonRequestData.OPTIONS_ELEMENT);
    if ((options != null) && !options.isJsonNull()) {
        if (!options.isJsonObject()) {
            RequestException ex = RequestException.forRequestMustBeAValidJsonObjectOrArray();
            logger.error(ex.getMessage(), ex);
            throw ex;
        }/* w w  w . ja  va 2  s . com*/
    }
    return (JsonObject) options;
}

From source file:com.solidfire.jsvcgen.serialization.OptionalAdapter.java

License:Open Source License

/**
 * Deserializes an Optional object./*from   ww  w  .  ja  v  a2s .c o m*/
 *
 * @param json    the element to deserialize.
 * @param typeOfT type of the expected return value.
 * @param context Context used for deserialization.
 * @return An Optional object containing an object of type typeOfT.
 */
public Optional<?> deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) {
    if (!json.isJsonObject() && !json.isJsonArray()) {
        if (json.isJsonNull() || json.getAsString() == null) {
            return Optional.empty();
        }
    }

    ParameterizedType pType = (ParameterizedType) typeOfT;
    Type genericType = pType.getActualTypeArguments()[0];

    // Special handling for string, "" will return Optional.of("")
    if (genericType.equals(String.class)) {
        return Optional.of(json.getAsString());
    }

    if (!json.isJsonObject() && !json.isJsonArray() && json.getAsString().trim().length() == 0) {
        return Optional.empty();
    }

    if (json.isJsonObject() || json.isJsonArray()) {
        if (json.isJsonNull()) {
            return Optional.empty();
        }
    }

    if (genericType.equals(Integer.class)) {
        return Optional.of(json.getAsInt());
    } else if (genericType.equals(Long.class)) {
        return Optional.of(json.getAsLong());
    } else if (genericType.equals(Double.class)) {
        return Optional.of(json.getAsDouble());
    }

    // Defer deserialization to handler for type contained in Optional
    Object obj = context.deserialize(json, genericType);
    OptionalAdaptorUtils.initializeAllNullOptionalFieldsAsEmpty(obj);
    return Optional.of(obj);
}

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

License:Open Source License

/**
 * If the given properties define {clock: 'name'}, and no 'clocks' property, transform to
 * {clocks: ['name']}.//from  w ww.  j a  va 2  s. c o m
 * 
 * @param properties
 */
protected final void applyClockShortcut(JsonObject properties) {
    JsonElement clock = properties.get(PROP_CLOCK);
    if (clock == null) {
        // no clock property, return
        return;
    }

    if (properties.has(PROP_CLOCKS)) {
        // both 'clock' and 'clocks' exist, show error and ignore 'clock'
        handler.addError(clock, "'clock' and 'clocks' are mutually exclusive");
        return;
    }

    if (clock.isJsonNull()) {
        // {clock: null} becomes {clocks: []}
        properties.add(PROP_CLOCKS, new JsonArray());
    } else if (clock.isJsonPrimitive() && clock.getAsJsonPrimitive().isString()) {
        // clock is valid, {clock: name} becomes {clocks: [name]}
        JsonArray clocksArray = new JsonArray();
        clocksArray.add(clock);
        properties.add(PROP_CLOCKS, clocksArray);
    } else {
        // clock not valid, ignore
        handler.addError(clock, "'clock' must be a valid clock name");
    }
}

From source file:com.tesla.framework.common.util.json.JSONHelper.java

License:Apache License

/**
 * @param element//from   ww  w  .  j  a  va 2  s .c o  m
 * @return ?element????
 * elementlist
 */
@NonNull
public static List<JsonObject> toJsonObjects(@NonNull JsonElement element) {
    Preconditions.checkNotNull(element);

    if (element.isJsonNull())
        return Collections.emptyList();

    List<JsonObject> list = new ArrayList<>();
    if (element.isJsonObject()) {
        list.add((JsonObject) element);
        return list;
    }

    if (element.isJsonArray()) {
        JsonArray arr = (JsonArray) element;
        Iterator<JsonElement> itr = arr.iterator();
        while (itr.hasNext()) {
            JsonElement e = itr.next();
            list.addAll(toJsonObjects(e));
        }

        return list;
    }

    return list;
}

From source file:com.torben.androidchat.JSONRPC.client.JsonRpcInvoker.java

License:Apache License

private Object invoke(String handleName, HttpJsonRpcClientTransport transport, Method method, Object[] args)
        throws Throwable {
    int id = rand.nextInt(Integer.MAX_VALUE);
    String methodName = handleName + "." + method.getName();

    JsonObject req = new JsonObject();
    req.addProperty("id", id);
    req.addProperty("method", methodName);

    JsonArray params = new JsonArray();
    if (args != null) {
        for (Object o : args) {
            params.add(gson.toJsonTree(o));
        }/*ww w .  j  a  v a2  s.  c  o m*/
    }
    req.add("params", params);

    String requestData = req.toString();
    LOG.debug("JSON-RPC >>  {}", requestData);
    //Log.v("JSON-RPC >>  {}", requestData);
    String responseData = null;

    responseData = transport.threadedCall(requestData);
    //Log.v("Invoker", "respondMSG: "+responseData);

    JsonParser parser = new JsonParser();
    JsonObject resp = (JsonObject) parser.parse(new StringReader(responseData));

    JsonElement result = resp.get("result");
    JsonElement error = resp.get("error");

    if (error != null && !error.isJsonNull()) {
        if (error.isJsonPrimitive()) {
            throw new JsonRpcRemoteException(error.getAsString());
        } else if (error.isJsonObject()) {
            JsonObject o = error.getAsJsonObject();
            Integer code = (o.has("code") ? o.get("code").getAsInt() : null);
            String message = (o.has("message") ? o.get("message").getAsString() : null);
            String data = (o.has("data") ? (o.get("data") instanceof JsonObject ? o.get("data").toString()
                    : o.get("data").getAsString()) : null);
            throw new JsonRpcRemoteException(code, message, data);
        } else {
            throw new JsonRpcRemoteException("unknown error, data = " + error.toString());
        }
    }

    if (method.getReturnType() == void.class) {
        return null;
    }

    return gson.fromJson(result.toString(), method.getReturnType());
}

From source file:com.totango.discoveryagent.gson.ValueDeserializer.java

License:Apache License

@Override
public Value deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {

    JsonObject jsonObj = (JsonObject) json;

    int createIndex = jsonObj.get("CreateIndex").getAsInt();
    int modifyIndex = jsonObj.get("ModifyIndex").getAsInt();
    int lockIndex = jsonObj.get("LockIndex").getAsInt();
    String key = jsonObj.get("Key").getAsString();
    int flags = jsonObj.get("Flags").getAsInt();
    JsonElement sessionJsonElement = jsonObj.get("Session");

    JsonElement valueJsonElement = jsonObj.get("Value");
    Optional<byte[]> value;
    if (valueJsonElement.isJsonNull()) {
        value = Optional.empty();
    } else {/*from w ww  .j a  v a2s  .  com*/
        value = Optional.of(jsonObj.get("Value").getAsString().getBytes(Charset.forName("UTF-8")));
    }

    Optional<String> session = Optional.ofNullable(sessionJsonElement).map(element -> element.getAsString());

    return new Value(key, value, createIndex, modifyIndex, lockIndex, flags, session);
}

From source file:com.tsc9526.monalisa.service.Response.java

License:Open Source License

public static Response fromJson(String jsonString) {
    JsonObject json = new JsonParser().parse(jsonString).getAsJsonObject();

    Response r = new Response();
    r.setStatus(json.get("status").getAsInt());
    r.setMessage(MelpJson.getString(json, "message"));

    JsonElement jd = json.get("data");
    if (jd != null && !jd.isJsonNull()) {
        if (jd.isJsonArray()) {
            JsonArray array = jd.getAsJsonArray();
            if (array.size() > 0 && array.get(0).isJsonObject()) {
                r.setData(MelpJson.parseToDataTable(array));
            } else if (array.size() == 0) {
                r.setData(new DataTable<DataMap>());
            } else {
                r.setData(jd);/*from  w ww .  ja  v  a 2s  .  co m*/
            }
        } else if (jd.isJsonObject()) {
            JsonObject js = jd.getAsJsonObject();
            if (js.get("total") != null && js.get("page") != null) {
                r.setData(MelpJson.parseToPage(jd.getAsJsonObject()));
            } else {
                r.setData(MelpJson.parseToDataMap(jd.getAsJsonObject()));
            }
        } else {
            r.setData(jd);
        }
    }
    return r;
}

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

License:Open Source License

public static String getString(JsonObject json, String name, String defaultValue) {
    JsonElement e = json.get(name);
    if (e == null || e.isJsonNull()) {
        return defaultValue;
    } else {//ww  w .ja v a  2 s .com
        return e.getAsString();
    }
}

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

License:Open Source License

public static int getInt(JsonObject json, String name, int defaultValue) {
    JsonElement e = json.get(name);
    if (e == null || e.isJsonNull()) {
        return defaultValue;
    } else {/*from  ww w  .ja  va2s .c o m*/
        return e.getAsInt();
    }
}

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

License:Open Source License

public static double getDouble(JsonObject json, String name, double defaultValue) {
    JsonElement e = json.get(name);
    if (e == null || e.isJsonNull()) {
        return defaultValue;
    } else {/*from w  w w .j a  va 2  s.  c  o m*/
        return e.getAsDouble();
    }
}