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.tesla.framework.common.util.json.JSONHelper.java

License:Apache License

@NonNull
public static Map<String, String> json2QueryMap(@NonNull JsonObject data) {
    Preconditions.checkNotNull(data);/*from w  w w. j  a  va2  s .  c  om*/

    Map<String, String> map = new HashMap<>();

    Set<Map.Entry<String, JsonElement>> set = data.entrySet();
    for (Map.Entry<String, JsonElement> entry : set) {

        String key = entry.getKey();
        if (TextUtils.isEmpty(key)) {
            continue;
        }

        JsonElement value = entry.getValue();
        if (value == null) {
            continue;
        }

        String content = value.isJsonPrimitive() ? value.getAsString() : value.toString();
        map.put(key, content);
    }

    return map;
}

From source file:com.thoughtworks.go.apiv1.secretconfigs.representers.RulesRepresenter.java

License:Apache License

private static Directive getDirective(JsonElement directiveJson) {
    JsonReader reader = GsonTransformer.getInstance().jsonReaderFrom(directiveJson.toString());
    String directive = reader.optString("directive").orElse(null);
    String action = reader.optString("action").orElse(null);
    String type = reader.optString("type").orElse(null);
    String resource = reader.optString("resource").orElse(null);

    Optional<DirectiveType> directiveType = fromString(directive);

    if (!directiveType.isPresent()) {
        return new Unknown(directive, action, type, resource);
    }/*  w  w  w  . j a va  2 s  .  c  om*/

    switch (directiveType.get()) {
    case ALLOW:
        return new Allow(action, type, resource);
    case DENY:
        return new Deny(action, type, resource);
    default:
        return new Unknown(directive, action, type, resource);
    }
}

From source file:com.thoughtworks.go.plugin.access.authorization.models.VerifyConnectionResponse.java

License:Apache License

private static ValidationResult validationResult(String json) {
    JsonObject jsonObject = GSON.fromJson(json, JsonObject.class);

    JsonElement errors = jsonObject.get("errors");

    return errors != null ? new JSONResultMessageHandler().toValidationResult(errors.toString()) : null;
}

From source file:com.threewks.thundr.elasticsearch.gae.model.ClientResponse.java

License:Apache License

private String getSourceAsJson() {
    JsonElement jsonElement = jsonObject.get("_source");
    return (jsonElement == null) ? null : jsonElement.toString();
}

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));
        }//from  ww  w .ja  va 2  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.torben.androidchat.JSONRPC.server.JsonRpcExecutor.java

License:Apache License

public Object[] getParameters(Method method, JsonArray params) {
    List<Object> list = new ArrayList<Object>();
    Class<?>[] types = method.getParameterTypes();
    for (int i = 0; i < types.length; i++) {
        JsonElement p = params.get(i);
        Object o = gson.fromJson(p.toString(), types[i]);
        list.add(o);/*from w w  w .  j  a v  a 2  s  . co  m*/
    }
    return list.toArray();
}

From source file:com.triarc.sync.SyncAdapter.java

License:Apache License

@SuppressLint("NewApi")
private void readResponse(SyncTypeCollection typeCollection, InputStream inputStream, HttpResponse response)
        throws UnsupportedEncodingException, IOException, JSONException, Exception {
    long lastUpdate = 0;
    Header header = response.getFirstHeader("X-Application-Timestamp");
    if (header != null) {
        String value = header.getValue();
        lastUpdate = Long.parseLong(value);
    }/*from w ww  . j  a v  a  2 s  .co m*/

    // json is UTF-8 by default
    BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
    JsonStreamParser parser = new JsonStreamParser(reader);
    JsonReader jsonReader = new JsonReader(reader);
    jsonReader.beginObject();
    jsonReader.nextName();
    jsonReader.beginObject();
    while (jsonReader.hasNext()) {

        String syncName = jsonReader.nextName();
        SyncType syncType = this.GetSyncType(typeCollection, syncName);

        JsonElement fromJson = new Gson().fromJson(jsonReader, JsonElement.class);
        updateLocalTypeData(fromJson.getAsJsonObject(), syncType, typeCollection, syncResult);

        notificationQueue.add(new SyncNotificationMessage(syncType, fromJson.toString()));
        // String path = jsonReader.getPath();
        // String nextName = jsonReader.nextName();
        // jsonReader.endObject();
    }
    jsonReader.endObject();

    // String json = getStringForReader(reader);
    //
    //
    // JSONObject syncChangeSets = new JSONObject(json)
    // .getJSONObject("changeSetPerType");
    //
    // // first save all
    // for (SyncType syncType : typeCollection.getTypes()) {
    // syncResult.madeSomeProgress();
    // String name = syncType.getName();
    //
    // if (syncChangeSets.has(name)) {
    // JSONObject changeSetObject = syncChangeSets.getJSONObject(name);
    // updateLocalTypeData(changeSetObject, syncType, typeCollection,
    // syncResult);
    // notificationMap.put(syncType, changeSetObject);
    // } else {
    // Log.w(TAG, "Server does not support syncing of " + name);
    // sendLogs();
    // }
    // }

    // store collection update timestamp
    PreferenceManager.getDefaultSharedPreferences(this.getContext()).edit()
            .putLong(typeCollection.getName(), lastUpdate).commit();
    // then notify all
    notifyWebApp();

}

From source file:com.tsc9526.monalisa.orm.tools.converters.impl.ArrayTypeConversion.java

License:Open Source License

protected Object convertJsonToArray(JsonArray array, Class<?> type) {
    Object value = null;// w w w.  j  a  va 2 s. c  o m
    if (type == int[].class) {
        int[] iv = new int[array.size()];
        for (int i = 0; i < array.size(); i++) {
            JsonElement e = array.get(i);
            iv[i] = e.getAsInt();
        }
        value = iv;
    } else if (type == float[].class) {
        float[] iv = new float[array.size()];
        for (int i = 0; i < array.size(); i++) {
            JsonElement e = array.get(i);
            iv[i] = e.getAsFloat();
        }
        value = iv;
    } else if (type == long[].class) {
        long[] iv = new long[array.size()];
        for (int i = 0; i < array.size(); i++) {
            JsonElement e = array.get(i);
            iv[i] = e.getAsLong();
        }
        value = iv;
    } else if (type == double[].class) {
        double[] iv = new double[array.size()];
        for (int i = 0; i < array.size(); i++) {
            JsonElement e = array.get(i);
            iv[i] = e.getAsDouble();
        }
        value = iv;
    } else {//String[]
        String[] iv = new String[array.size()];
        for (int i = 0; i < array.size(); i++) {
            JsonElement e = array.get(i);
            if (e.isJsonPrimitive()) {
                iv[i] = e.getAsString();
            } else {
                iv[i] = e.toString();
            }
        }
        value = iv;
    }

    return value;
}

From source file:com.unovo.frame.utils.gson.deserializer.DateJsonDeserializer.java

License:Open Source License

@Override
public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {
    try {//from  w  w  w .  j  a  v  a 2 s.  c o  m
        //SimpleFormatter
        //return json.getda();
        return null;
    } catch (Exception e) {
        Logger.i("DateJsonDeserializer-deserialize-error:" + (json != null ? json.toString() : ""));
        return null;
    }
}

From source file:com.unovo.frame.utils.gson.deserializer.DoubleJsonDeserializer.java

License:Open Source License

@Override
public Double deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {
    try {/*from w  w w . j  a va 2 s.c  o m*/
        return json.getAsDouble();
    } catch (Exception e) {
        Logger.i("DoubleJsonDeserializer-deserialize-error:" + (json != null ? json.toString() : ""));
        return 0D;
    }
}