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.microsoft.windowsazure.mobileservices.table.serialization.JsonEntityParser.java

License:Open Source License

/**
 * Changes returned JSon object's id property name to match with type's id
 * property name.//w  w  w .ja  va 2 s  .  c o m
 *
 * @param element
 * @param propertyName
 */
private static void changeIdPropertyName(JsonObject element, String propertyName) {
    // If the property name is id or if there's no id defined, then return
    // without performing changes
    if (propertyName.equals("id") || propertyName.length() == 0)
        return;

    if (element.has("id")) {

        JsonElement idElement = element.get("id");

        String value = idElement.isJsonNull() ? null : idElement.getAsString();
        element.remove("id");

        // Create a new id property using the given property name
        element.addProperty(propertyName, value);
    }
}

From source file:com.microsoft.windowsazure.mobileservices.table.sync.localstore.SQLiteLocalStore.java

License:Open Source License

private void appendInsertValuesSql(StringBuilder sql, List<Object> parameters,
        Map<String, ColumnDataInfo> tableDefinition, JsonObject item, boolean fromServer) {
    sql.append("(");
    int colCount = 0;

    for (Entry<String, JsonElement> property : item.entrySet()) {

        if (fromServer && !tableDefinition.containsKey(normalizeColumnName(property.getKey()))) {
            continue;
        }//from w ww.j ava2 s  . com

        if (colCount > 0)
            sql.append(",");

        String paramName = "@p" + parameters.size();

        JsonElement value = property.getValue();

        if (value.isJsonNull()) {
            parameters.add(null);
        } else if (value.isJsonPrimitive()) {
            if (value.getAsJsonPrimitive().isBoolean()) {
                long longVal = value.getAsJsonPrimitive().getAsBoolean() ? 1L : 0L;
                parameters.add(longVal);
            } else if (value.getAsJsonPrimitive().isNumber()) {
                parameters.add(value.getAsJsonPrimitive().getAsDouble());
            } else {
                parameters.add(value.getAsJsonPrimitive().getAsString());
            }
        } else {
            parameters.add(value.toString());
        }

        sql.append(paramName);
        colCount++;

    }

    sql.append(")");
}

From source file:com.microsoft.windowsazure.mobileservices.table.sync.MobileServiceSyncTable.java

License:Open Source License

/**
 * Insert an item into the local table and enqueue the operation to be
 * synchronized on context push./*from www  . j a va2  s.  co m*/
 *
 * @param item the item to be inserted
 * @return A ListenableFuture that is done when the item has been inserted,
 * returning a copy of the inserted item including id.
 */
public ListenableFuture<E> insert(E item) {
    final SettableFuture<E> future = SettableFuture.create();

    final JsonObject json = mClient.getGsonBuilder().create().toJsonTree(item).getAsJsonObject();

    JsonElement idJsonObject = json.get("id");

    if (idJsonObject != null && !idJsonObject.isJsonNull()) {
        String itemId = idJsonObject.getAsString();

        ListenableFuture<JsonObject> lookUpInternalFuture = mInternalTable.lookUp(itemId);

        Futures.addCallback(lookUpInternalFuture, new FutureCallback<JsonObject>() {
            @Override
            public void onFailure(Throwable throwable) {
                future.setException(throwable);
            }

            @Override
            public void onSuccess(JsonObject result) {

                if (result != null) {
                    future.set(parseResults(result).get(0));
                    return;
                }

                insertInternal(json, future);
            }
        });
    } else {
        insertInternal(json, future);
    }

    return future;
}

From source file:com.money.manager.ex.investment.yql.YqlSecurityPriceUpdaterRetrofit.java

License:Open Source License

private Money readPrice(String priceString, JsonObject quote) {
    UIHelper ui = new UIHelper(getContext());
    Money price = MoneyFactory.fromString(priceString);

    /**/*from w w w .ja v  a2 s . c o m*/
     LSE stocks are expressed in GBp (pence), not Pounds.
     From stockspanel.cpp, line 785: if (StockQuoteCurrency == "GBp") dPrice = dPrice / 100;
     */
    JsonElement currencyElement = quote.get("Currency");

    // validation
    if (currencyElement == null || currencyElement.isJsonNull()) {
        ui.showToast(R.string.error_downloading_symbol);
        return MoneyFactory.fromDouble(0);
    }

    String currency;
    try {
        currency = currencyElement.getAsString();
    } catch (UnsupportedOperationException ex) {
        Timber.e(ex, "reading currency from downloaded price");
        currency = "";
    }
    if (currency.equals("GBp")) {
        price = price.divide(100, MoneyFactory.MAX_ALLOWED_PRECISION);
    }
    return price;
}

From source file:com.nextdoor.bender.operation.json.key.FlattenOperation.java

License:Apache License

protected void perform(JsonObject obj) {

    Set<Entry<String, JsonElement>> entries = obj.entrySet();
    Set<Entry<String, JsonElement>> orgEntries = new HashSet<Entry<String, JsonElement>>(entries);

    for (Entry<String, JsonElement> entry : orgEntries) {
        JsonElement val = entry.getValue();

        if (val.isJsonPrimitive() || val.isJsonNull()) {
            continue;
        }//from w w w  .j  av a2 s.  c  om

        obj.remove(entry.getKey());
        if (val.isJsonObject()) {
            perform(obj, val.getAsJsonObject(), entry.getKey());
        } else if (val.isJsonArray()) {
            perform(obj, val.getAsJsonArray(), entry.getKey());
        }
    }
}

From source file:com.nimbits.server.gson.deserializer.ValueDeserializer.java

License:Apache License

@Override
public Value deserialize(final JsonElement jsonElement, final Type type,
        final JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
    Location location;/*from   w  w  w.  j a va2  s .c o m*/

    JsonObject jsonObject = jsonElement.getAsJsonObject();
    JsonElement valueElement = jsonObject.get("d");
    JsonElement dataElement = jsonObject.get("dx");
    JsonElement latElement = jsonObject.get("lt");
    JsonElement lngElement = jsonObject.get("lg");
    JsonElement timestampElement = jsonObject.get("t");
    String data = dataElement == null ? null : dataElement.getAsString();
    Double lat = latElement == null || latElement.isJsonNull() ? null : latElement.getAsDouble();
    Double lng = lngElement == null || lngElement.isJsonNull() ? null : lngElement.getAsDouble();
    Double value = valueElement == null || valueElement.isJsonNull() ? null : valueElement.getAsDouble();
    Long timestamp = timestampElement == null || timestampElement.isJsonNull() ? 0
            : timestampElement.getAsLong();

    if (lat != null && lng != null) {
        location = LocationFactory.createLocation(lat, lng);
    } else {
        location = LocationFactory.createEmptyLocation();
    }

    Date time = timestamp > 0 ? new Date(timestamp) : new Date();
    ValueData valueData;
    if (data != null && data.length() > 0) {
        valueData = ValueDataModel.getInstance(SimpleValue.getInstance(data));
    } else {
        valueData = ValueDataModel.getEmptyInstance();
    }

    return ValueFactory.createValueModel(location, value, time, valueData, AlertType.OK);

}

From source file:com.openyelp.client.JsonRpcInvoker.java

License:Apache License

private Object work(String handleName, JsonRpcClientTransport transport, Method method, Object[] args,
        String key) {//w w w.  j av a  2s  .  c om
    Gson gson = new Gson();
    String cachekey = handleName + method.getName() + getKey(args);
    String keyy = Utils.getMD5Str(cachekey);
    String responseData = null;
    if (cache != null) {
        responseData = cache.get(keyy);
        if (responseData == null) {
            responseData = c(handleName, transport, method, args, key, gson);
            cache.put(keyy, responseData);
        }
    } else {
        responseData = c(handleName, transport, method, args, key, gson);
    }
    if (responseData == null) {
        if (diskCache != null) {
            responseData = diskCache.get(keyy);
        }
    }
    if (responseData == null) {
        return null;
    }

    JsonParser parser = new JsonParser();
    JsonObject resp = (JsonObject) parser.parse(new StringReader(responseData));
    // int sid = resp.get("id").getAsInt();
    // if (id == sid) {
    // } else {
    // return null;
    // }
    JsonElement result = resp.get("result");
    JsonElement error = resp.get("error");
    /**
     * ?null
     */
    if (error != null && !error.isJsonNull()) {
        if (error.isJsonPrimitive()) {
            System.out.println("<<>>>>>" + 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);
            System.out.println(message + "<<>>>>>" + data);
        } else {
            System.out.println("<<>>>>>" + error.toString());
        }
        return null;
    }
    if (diskCache != null) {
        System.out.println("?");
        diskCache.put(keyy, responseData);
    }
    if (method.getReturnType() == void.class) {
        return null;
    }
    return gson.fromJson(result.toString(), method.getReturnType());
}

From source file:com.optimizely.ab.config.parser.GsonHelpers.java

License:Apache License

static Experiment parseExperiment(JsonObject experimentJson, String groupId,
        JsonDeserializationContext context) {
    String id = experimentJson.get("id").getAsString();
    String key = experimentJson.get("key").getAsString();
    JsonElement experimentStatusJson = experimentJson.get("status");
    String status = experimentStatusJson.isJsonNull() ? ExperimentStatus.NOT_STARTED.toString()
            : experimentStatusJson.getAsString();

    JsonElement layerIdJson = experimentJson.get("layerId");
    String layerId = layerIdJson == null ? null : layerIdJson.getAsString();

    JsonArray audienceIdsJson = experimentJson.getAsJsonArray("audienceIds");
    List<String> audienceIds = new ArrayList<>(audienceIdsJson.size());
    for (JsonElement audienceIdObj : audienceIdsJson) {
        audienceIds.add(audienceIdObj.getAsString());
    }/*from  ww  w  . j ava2 s. c om*/

    Condition conditions = parseAudienceConditions(experimentJson);

    // parse the child objects
    List<Variation> variations = parseVariations(experimentJson.getAsJsonArray("variations"), context);
    Map<String, String> userIdToVariationKeyMap = parseForcedVariations(
            experimentJson.getAsJsonObject("forcedVariations"));
    List<TrafficAllocation> trafficAllocations = parseTrafficAllocation(
            experimentJson.getAsJsonArray("trafficAllocation"));

    return new Experiment(id, key, status, layerId, audienceIds, conditions, variations,
            userIdToVariationKeyMap, trafficAllocations, groupId);
}

From source file:com.pinterest.deployservice.common.AlarmDataFactory.java

License:Apache License

/**
 * Take a JSON string and convert into a list of Alarm configs.
 *///www .  j ava 2  s  .  com
public List<AlarmBean> fromJson(String payload) {
    if (StringUtils.isEmpty(payload)) {
        return Collections.emptyList();
    }

    List<AlarmBean> configs = new ArrayList<>();
    JsonParser parser = new JsonParser();
    JsonObject jsonObj = (JsonObject) parser.parse(payload);
    JsonArray arrayOfUrls = jsonObj.getAsJsonArray(ALARM_ARRAY);
    for (int i = 0; i < arrayOfUrls.size(); i++) {
        JsonObject urlObj = arrayOfUrls.get(i).getAsJsonObject();
        AlarmBean config = new AlarmBean();
        config.setName(urlObj.get(NAME).getAsString());
        config.setAlarmUrl(urlObj.get(ALARM_URL).getAsString());
        JsonElement element = urlObj.get(METRICS_URL);
        if (!element.isJsonNull()) {
            config.setMetricsUrl(element.getAsString());
        }
        configs.add(config);
    }
    return configs;
}

From source file:com.pinterest.deployservice.common.WebhookDataFactory.java

License:Apache License

private String getString(JsonObject hookObj, String name) {
    JsonElement element = hookObj.get(name);
    if (element.isJsonNull()) {
        return null;
    } else {/*from   w  w w  . j a v a  2  s.co  m*/
        return element.getAsString();
    }
}