Example usage for com.google.gson JsonObject remove

List of usage examples for com.google.gson JsonObject remove

Introduction

In this page you can find the example usage for com.google.gson JsonObject remove.

Prototype

public JsonElement remove(String property) 

Source Link

Document

Removes the property from this JsonObject .

Usage

From source file:com.paysafe.common.impl.AddressContainerAdapter.java

License:Open Source License

/**
 * Serialize the object with all addressDetails properties within the base object.
 *
 * @param addressContainer the address container
 * @param typeOfSrc the type of src//from ww w . j  ava2 s.  co m
 * @param context the context
 * @return the json element
 */
@Override
public JsonElement serialize(final AddressContainer addressContainer, final Type typeOfSrc,
        final JsonSerializationContext context) {

    final JsonElement base = gsonSerializer.toJsonTree(addressContainer);
    if (base.isJsonObject()) {
        final JsonObject baseObj = base.getAsJsonObject();
        if (baseObj.has("addressDetails")) {
            final JsonElement details = baseObj.get("addressDetails");
            baseObj.remove("addressDetails");
            for (Map.Entry<String, JsonElement> entry : details.getAsJsonObject().entrySet()) {
                baseObj.add(entry.getKey(), entry.getValue());
            }
        }
    }
    return base;
}

From source file:com.simiacryptus.mindseye.lang.Layer.java

License:Apache License

/**
 * As t.//from  w w  w  . ja  va 2  s  .c om
 *
 * @param <T>         the type parameter
 * @param targetClass the target class
 * @return the t
 */
@Nonnull
@SuppressWarnings("unchecked")
default <T extends Layer> T as(@Nonnull final Class<T> targetClass) {
    @Nonnull
    HashMap<CharSequence, byte[]> resources = new HashMap<>();
    final JsonObject json = getJson(resources, SerialPrecision.Double);
    json.remove("class");
    json.addProperty("class", targetClass.getCanonicalName());
    return (T) fromJson(json, resources);
}

From source file:com.srotya.tau.dengine.validation.DateInterceptor.java

License:Apache License

@Override
public void validate(JsonObject event) throws ValidationException {
    try {//from   ww  w  .  j a  va  2 s  .  c  om
        DateTime ts = formatter.parseDateTime(event.get(dateField).getAsString());
        event.remove(dateField);
        event.addProperty(dateField, ts.getMillis());
        if (next != null) {
            next.validate(event);
        }
    } catch (Exception e) {
        throw new ValidationException(e.getMessage());
    }
}

From source file:com.stackmob.sdk.api.StackMobDatastore.java

License:Apache License

/**
 * do a PUT request on the StackMob platform, treating some of the fields as counters to be incremented rather
 * than as values to set/*www . java  2s.  c  om*/
 * @param path the path to put
 * @param id the id of the object to put
 * @param requestObject the object to serialize and send in the PUT body. this object will be serialized with Gson
 * @param counterFields a list of the fields in the object to be treated as counters being incremented
 * @param callback callback to be called when the server returns. may execute in a separate thread
 */
public void putAndUpdateAtomicCounters(String path, String id, Object requestObject, List<String> counterFields,
        StackMobRawCallback callback) {
    JsonObject obj = new Gson().toJsonTree(requestObject).getAsJsonObject();
    for (Map.Entry<String, JsonElement> field : new HashSet<Map.Entry<String, JsonElement>>(obj.entrySet())) {
        if (counterFields.contains(field.getKey())) {
            obj.remove(field.getKey());
            obj.add(field.getKey() + "[inc]", field.getValue());
        }
    }
    put(path, id, obj.toString(), callback);
}

From source file:com.stackmob.sdk.model.StackMobModel.java

License:Apache License

private JsonElement toJsonElement(int depth, RelationMapping mapping) {
    // Set the id here as opposed to on the server to avoid a race condition
    if (getID() == null)
        setID(UUID.randomUUID().toString().replace("-", ""));
    if (depth < 0)
        return new JsonPrimitive(getID());
    JsonObject json = gson.toJsonTree(this).getAsJsonObject();
    JsonObject outgoing = new JsonObject();
    for (String fieldName : getFieldNames(json)) {
        ensureValidName(fieldName, "field");
        JsonElement value = json.get(fieldName);
        if (getMetadata(fieldName) == MODEL) {
            json.remove(fieldName);
            try {
                Field relationField = getField(fieldName);
                relationField.setAccessible(true);
                StackMobModel relatedModel = (StackMobModel) relationField.get(this);
                mapping.add(fieldName, relatedModel.getSchemaName());
                JsonElement relatedJson = relatedModel.toJsonElement(depth - 1, mapping);
                mapping.leave();/*from   ww  w .  j  a  v  a  2s.  com*/
                if (relatedJson != null)
                    json.add(fieldName, relatedJson);
            } catch (Exception ignore) {
            } //Should never happen
        } else if (getMetadata(fieldName) == MODEL_ARRAY) {
            json.remove(fieldName);
            try {
                Field relationField = getField(fieldName);
                relationField.setAccessible(true);
                JsonArray array = new JsonArray();
                Collection<StackMobModel> relatedModels;
                if (relationField.getType().isArray()) {
                    relatedModels = Arrays.asList((StackMobModel[]) relationField.get(this));
                } else {
                    relatedModels = (Collection<StackMobModel>) relationField.get(this);
                }
                boolean first = true;
                for (StackMobModel relatedModel : relatedModels) {
                    if (first) {
                        mapping.add(fieldName, relatedModel.getSchemaName());
                        first = false;
                    }
                    JsonElement relatedJson = relatedModel.toJsonElement(depth - 1, mapping);
                    if (relatedJson != null)
                        array.add(relatedJson);
                }
                if (!first)
                    mapping.leave();
                json.add(fieldName, array);
            } catch (Exception ignore) {
            } //Should never happen
        } else if (getMetadata(fieldName) == OBJECT) {
            //We don't support subobjects. Gson automatically converts a few types like
            //Date and BigInteger to primitive types, but anything else has to be an error.
            if (value.isJsonObject()) {
                throw new IllegalStateException(
                        "Field " + fieldName + " is a subobject which is not supported at this time");
            }
        }
        outgoing.add(fieldName.toLowerCase(), json.get(fieldName));
    }
    if (id != null) {
        outgoing.addProperty(getIDFieldName(), id);
    }
    return outgoing;
}

From source file:com.thoughtworks.go.plugin.configrepo.codec.TaskTypeAdapter.java

License:Apache License

@Override
public JsonElement serialize(CRTask crTask, Type type, JsonSerializationContext context) {
    JsonObject retValue = context.serialize(crTask).getAsJsonObject();
    CRTask onCancel = crTask.getOnCancel();
    if (onCancel != null) {
        retValue.remove("onCancel");
        retValue.add("onCancel", context.serialize(onCancel));
    }//from  w ww.j a  va  2 s .c o  m

    return retValue;
}

From source file:com.torben.androidchat.JSONRPC.server.JsonRpcExecutor.java

License:Apache License

private void sendError(HttpJsonRpcClientTransport transport, JsonObject resp, Integer code, String message,
        String data) {//  w  w w . ja v a2  s  .c  o  m
    JsonObject error = new JsonObject();
    if (code != null) {
        error.addProperty("code", code);
    }

    if (message != null) {
        error.addProperty("message", message);
    }

    if (data != null) {
        error.addProperty("data", data);
    }

    resp.add("error", error);
    resp.remove("result");
    String responseData = resp.toString();

    LOG.debug("JSON-RPC error <<  {}", responseData);
    try {
        transport.threadedCall(responseData);
    } catch (Exception e) {
        LOG.error("unable to write error response : " + responseData, e);
    }
}

From source file:com.vaadin.addon.charts.model.gsonhelpers.AbstractSeriesTypeAdapterFactory.java

private TypeAdapter<AbstractSeries> customizeMyClassAdapter(Gson gson, TypeToken<AbstractSeries> type) {
    final TypeAdapter<AbstractSeries> delegate = gson.getDelegateAdapter(this, type);
    final TypeAdapter<JsonElement> elementAdapter = gson.getAdapter(JsonElement.class);
    return new TypeAdapter<AbstractSeries>() {
        @Override/*from ww  w . j  a v a  2 s.c om*/
        public void write(JsonWriter out, AbstractSeries value) throws IOException {
            JsonObject tree = (JsonObject) delegate.toJsonTree(value);

            // "flatten" series specific plot options at series level. see
            // Higchart API for details
            if (value.getPlotOptions() != null) {
                JsonObject plotOptionsJson = (JsonObject) tree.remove("plotOptions");
                if (plotOptionsJson != null) {
                    Set<Entry<String, JsonElement>> entrySet = plotOptionsJson.entrySet();
                    for (Entry<String, JsonElement> entry : entrySet) {
                        tree.add(entry.getKey(), entry.getValue());
                    }
                    tree.addProperty("type", value.getPlotOptions().getChartType().toString());
                }
            }
            elementAdapter.write(out, tree);
        }

        // This is never used
        @Override
        public AbstractSeries read(JsonReader in) throws IOException {
            JsonElement tree = elementAdapter.read(in);
            return delegate.fromJsonTree(tree);
        }
    };
}

From source file:com.vmware.admiral.test.upgrade.version2.UpgradeNewService3StateConverter.java

License:Open Source License

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

    try {// w  w  w .j  av  a 2  s. c  o m
        return JSON_MAPPER.fromJson(json, UpgradeNewService3State.class);
    } catch (JsonSyntaxException e) {
        JsonObject jsonObject = json.getAsJsonObject();

        // ---- custom transformation logic here ---

        // "field3" upgrade: String -> Long

        JsonElement field3 = jsonObject.remove("field3");
        String oldField3Value = field3.getAsString();
        Long newField3Value = ("fortytwo".equals(oldField3Value)) ? 42L : 0L;
        jsonObject.addProperty("field3", newField3Value);

        // "field5" upgrade: List ("a", "b", "c") -> Map ("a=a", "b=b", "c=c")

        // JsonElement field5 = jsonObject.remove("field5");
        // List<String> oldField5Value = Utils.fromJson(field5, List.class);
        // Map<String, String> newField5Value = oldField5Value.stream()
        // .collect(Collectors.toMap(Function.identity(), Function.identity()));
        // jsonObject.add("field5", JSON_PARSER.parse(Utils.toJson(newField5Value)));

        return JSON_MAPPER.fromJson(json, UpgradeNewService3State.class);
    }
}

From source file:com.vmware.admiral.test.upgrade.version2.UpgradeNewService3StateConverter.java

License:Open Source License

@Override
public JsonElement serialize(UpgradeNewService3State state, Type typeOfSrc, JsonSerializationContext context) {

    String version = ThreadLocalVersionHolder.getVersion();

    String json = JSON_MAPPER.toJson(state);
    JsonElement jsonElement = JSON_PARSER.parse(json);

    if (ReleaseConstants.API_VERSION_0_9_1.equals(version)) {

        /*/*from  w  w  w  . j a va2s .  c  o  m*/
         * Handle the backward compatibility with the previous version
         */
        JsonObject jsonObject = jsonElement.getAsJsonObject();

        // "field3" upgrade: Long -> String

        JsonElement field3 = jsonObject.remove("field3");
        Long oldField3Value = field3.getAsLong();
        String newField3Value = (oldField3Value == 42L) ? "fortytwo" : "";
        jsonObject.addProperty("field3", newField3Value);

        // "field5" upgrade: Map ("a=a", "b=b", "c=c") -> List ("a", "b", "c")

        // JsonElement field5 = jsonObject.remove("field5");
        // Map<String, String> oldField5Value = Utils.fromJson(field5, Map.class);
        // List<String> newField5Value = new ArrayList<>(oldField5Value.keySet());
        // jsonObject.add("field5", JSON_PARSER.parse(Utils.toJson(newField5Value)));
    }

    return jsonElement;
}