Example usage for com.google.gson JsonElement toString

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

Introduction

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

Prototype

@Override
public String toString() 

Source Link

Document

Returns a String representation of this element.

Usage

From source file:com.microsoft.azure.sdk.iot.deps.serializer.TwinTags.java

License:Open Source License

private synchronized JsonElement updateFromMap(Map<String, Object> newMap, Map<String, Object> oldMap)
        throws IllegalArgumentException {
    JsonObject diffJson = new JsonObject();

    /* Codes_SRS_TWINPARSER_21_103: [The updateTags shall add all provided tags to the collection.] */
    for (Map.Entry<String, Object> entry : newMap.entrySet()) {
        String key = entry.getKey();
        Object newValue = entry.getValue();
        Object oldValue = oldMap.get(key);

        if (newValue == null) {
            oldMap.put(key, null);//from  w  w  w.  j a  v a 2s  .c om
        } else {
            if (!oldMap.containsKey(key)) {
                if (newValue instanceof Map) {
                    oldMap.put(key, new HashMap<String, Object>());
                    diffJson.add(key, updateFromMap((Map<String, Object>) newValue,
                            (Map<String, Object>) oldMap.get(key)));
                } else {
                    oldMap.put(key, newValue);
                    addProperty(diffJson, key, newValue);
                }
            } else {
                if (newValue instanceof Map) {
                    if (!(oldValue instanceof Map)) {
                        oldMap.put(key, new HashMap<String, Object>());
                    }
                    JsonElement innerDiff = updateFromMap((Map<String, Object>) newValue,
                            (Map<String, Object>) oldMap.get(key));
                    if ((innerDiff != null) && (!innerDiff.toString().equals("{}"))) {
                        diffJson.add(key, innerDiff);
                    }
                } else if (!newValue.equals(oldValue)) {
                    oldMap.put(key, newValue);
                    addProperty(diffJson, key, newValue);
                }
            }
        }
    }

    return (JsonElement) diffJson;
}

From source file:com.microsoft.graph.serializer.DefaultSerializer.java

License:Open Source License

/**
 * Serializes an object into a string.//  w w w  .j  a v  a 2s  . c  o m
 *
 * @param serializableObject The object to convert into a string.
 * @param <T>                The type of the item to be serialized.
 * @return The string representation of that item.
 */
@Override
public <T> String serializeObject(final T serializableObject) {
    mLogger.logDebug("Serializing type " + serializableObject.getClass().getSimpleName());
    JsonElement outJsonTree = mGson.toJsonTree(serializableObject);

    if (serializableObject instanceof IJsonBackedObject) {
        AdditionalDataManager additionalData = ((IJsonBackedObject) serializableObject)
                .getAdditionalDataManager();
        if (outJsonTree.isJsonObject()) {
            JsonObject outJson = outJsonTree.getAsJsonObject();
            for (Map.Entry<String, JsonElement> entry : additionalData.entrySet()) {
                if (!fieldIsOdataTransient(entry)) {
                    outJson.add(entry.getKey(), entry.getValue());
                }
            }
            outJsonTree = outJson;
        }
    }

    return outJsonTree.toString();
}

From source file:com.microsoft.onenoteapi.service.PatchCommand.java

License:MIT License

@Override
public JsonElement serialize(PatchCommand patchCommand, Type typeOfSrc, JsonSerializationContext context) {
    JsonElement result = new GsonBuilder().create().toJsonTree(patchCommand);
    Log.i(getClass().getSimpleName(), result.toString());
    return result;
}

From source file:com.microsoft.windowsazure.mobileservices.MobileServicePush.java

License:Open Source License

/**
 * Updates a registration/*from w  w  w .  ja  va  2s .  c  om*/
 * 
 * @param registration
 *            The registration to update
 * @param callback
 *            The operation callback
 */
private void upsertRegistrationInternal(final Registration registration,
        final UpsertRegistrationInternalCallback callback) {

    GsonBuilder gsonBuilder = new GsonBuilder();
    gsonBuilder = gsonBuilder.excludeFieldsWithoutExposeAnnotation();

    Gson gson = gsonBuilder.create();

    String resource = registration.getURI();
    JsonElement json = gson.toJsonTree(registration);
    String body = json.toString();
    byte[] content = null;

    try {
        content = body.getBytes(MobileServiceClient.UTF8_ENCODING);
    } catch (UnsupportedEncodingException e) {
        callback.onUpsert(registration, e);
        return;
    }

    List<Pair<String, String>> requestHeaders = new ArrayList<Pair<String, String>>();

    requestHeaders.add(new Pair<String, String>(HTTP.CONTENT_TYPE, MobileServiceConnection.JSON_CONTENTTYPE));

    mClient.invokeApiInternal(resource, content, "PUT", requestHeaders, null, MobileServiceClient.PNS_API_URL,
            new ServiceFilterResponseCallback() {

                @Override
                public void onResponse(ServiceFilterResponse response, Exception exception) {
                    if (exception != null) {
                        if (response.getStatus().getStatusCode() == 410) {
                            exception = new RegistrationGoneException(exception);
                        }

                        callback.onUpsert(registration, exception);

                        return;
                    } else {
                        callback.onUpsert(registration, null);

                        return;
                    }
                }
            });
}

From source file:com.microsoft.windowsazure.mobileservices.notifications.MobileServicePush.java

License:Open Source License

/**
 * Updates a registration//  ww  w. jav  a 2 s  . co m
 *
 * @param registration The registration to update
 * @param callback     The operation callback
 * @throws java.io.UnsupportedEncodingException
 * @throws Exception
 */
private ListenableFuture<Void> upsertRegistrationInternal(final Registration registration) {

    final SettableFuture<Void> resultFuture = SettableFuture.create();

    GsonBuilder gsonBuilder = new GsonBuilder();
    gsonBuilder = gsonBuilder.excludeFieldsWithoutExposeAnnotation();

    Gson gson = gsonBuilder.create();

    String resource = registration.getURI();
    String path = PNS_API_URL + resource;
    JsonElement json = gson.toJsonTree(registration);
    String body = json.toString();

    byte[] content;
    try {
        content = body.getBytes(MobileServiceClient.UTF8_ENCODING);
    } catch (UnsupportedEncodingException e) {
        resultFuture.setException(e);
        return resultFuture;
    }

    List<Pair<String, String>> requestHeaders = new ArrayList<Pair<String, String>>();

    requestHeaders.add(new Pair<String, String>(HTTP.CONTENT_TYPE, MobileServiceConnection.JSON_CONTENTTYPE));

    ListenableFuture<ServiceFilterResponse> serviceFilterFuture = mHttpClient.request(path, content, "PUT",
            requestHeaders, null);

    Futures.addCallback(serviceFilterFuture, new FutureCallback<ServiceFilterResponse>() {
        @Override
        public void onFailure(Throwable exception) {
            resultFuture.setException(exception);
        }

        @Override
        public void onSuccess(ServiceFilterResponse response) {
            resultFuture.set(null);
        }
    });

    return resultFuture;
}

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  w  w .  j  a v  a 2s .  c o  m*/

        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.myjeeva.digitalocean.Utils.java

License:Open Source License

public static Object byClass(JsonElement jsonElement, Class<?> clazz) {
    return getGson().fromJson(jsonElement.toString(), clazz);
}

From source file:com.myjeeva.digitalocean.Utils.java

License:Open Source License

public static Object byType(JsonElement jsonElement, Type type) {
    return getGson().fromJson(jsonElement.toString(), type);
}

From source file:com.nextdoor.bender.operation.json.array.ArraySplitOperation.java

License:Apache License

@Override
public List<InternalEvent> perform(InternalEvent ievent) throws OperationException {
    {//from   w  w w .j a v  a 2s  .c  o  m
        if (ievent.getEventObj() == null) {
            throw new OperationException("Deserialized object is null");
        }

        Object payload;
        try {
            payload = ievent.getEventObj().getField(this.path);
        } catch (FieldNotFoundException e) {
            throw new OperationException(e);
        }

        if (!(payload instanceof JsonArray)) {
            throw new OperationException("Payload data is not a JsonArray");
        }

        LinkedHashMap<String, String> partitions = ievent.getPartitions();

        JsonArray arr = (JsonArray) payload;

        ArrayList<InternalEvent> output = new ArrayList<InternalEvent>();
        for (JsonElement elm : arr) {
            try {
                InternalEvent newEvent = new InternalEvent(elm.toString(), ievent.getCtx(),
                        ievent.getArrivalTime());
                DeserializedEvent newDeserEvent = new GenericJsonEvent(elm.getAsJsonObject());
                newEvent.setEventObj(newDeserEvent);
                newEvent.setEventTime(ievent.getEventTime());

                /*
                 * Deep clone the partitions
                 */
                if (partitions != null) {
                    LinkedHashMap<String, String> newPartitions = new LinkedHashMap<String, String>(
                            partitions.size());

                    partitions.entrySet().forEach(kv -> {
                        newPartitions.put(new String(kv.getKey()), new String(kv.getValue()));
                    });

                    newEvent.setPartitions(newPartitions);
                }

                output.add(newEvent);
            } catch (Exception e) {
                throw new OperationException(e);
            }
        }

        return output;
    }
}

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

License:Apache License

@Override
public Category deserialize(final JsonElement jsonElement, final Type type,
        final JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {

    final String json = jsonElement.toString();
    Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
    return gson.fromJson(json, CategoryModel.class);

}