Example usage for com.google.gson JsonElement getAsString

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

Introduction

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

Prototype

public String getAsString() 

Source Link

Document

convenience method to get this element as a string value.

Usage

From source file:com.dell.prototype.apm.server.AppServerMonitorDataSubmissionServlet.java

License:Open Source License

@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) {
    String line = "";
    try {/*from   w w w  .  j  a va2s.  c  om*/
        line = request.getReader().readLine();
    } catch (IOException e) {
        e.printStackTrace();
    }
    String[] msgs = line.split(";;");
    List<Request> requests = new ArrayList<Request>();

    Gson gson = new GsonBuilder()
            .registerTypeAdapter(RequestTiming.class, new JsonDeserializer<RequestTiming>() {
                @Override
                public RequestTiming deserialize(JsonElement jsonElement, Type type,
                        JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
                    if (!jsonElement.isJsonObject())
                        return new RequestTiming();

                    String name = ((JsonObject) jsonElement).getAsJsonPrimitive("name").getAsString();
                    if ("database".equals(name)) {
                        DatabaseTiming databaseTiming = new DatabaseTiming(name);
                        databaseTiming
                                .setTime(((JsonObject) jsonElement).getAsJsonPrimitive("time").getAsLong());
                        String sql = ((JsonObject) jsonElement).getAsJsonPrimitive("sql").getAsString();
                        databaseTiming.setSql(sql);
                        List<String> bindingParameters = new ArrayList<String>();
                        for (JsonElement bindParameter : ((JsonObject) jsonElement).get("bindingParameters")
                                .getAsJsonArray()) {
                            bindingParameters.add(bindParameter.getAsString());
                        }
                        databaseTiming.setBindingParameters(bindingParameters);
                        return databaseTiming;
                    }
                    RequestTiming requestTiming = new RequestTiming();
                    requestTiming.setName("server");
                    requestTiming.setTime(((JsonObject) jsonElement).getAsJsonPrimitive("time").getAsLong());
                    return requestTiming;
                }
            }).create();
    for (int i = 0; i < msgs.length - 1; i++) {
        if (null != msgs[i] && !"".equals(msgs[i])) {
            requests.add(gson.fromJson(msgs[i], Request.class));
        }
    }
    String jvmMsg = msgs[msgs.length - 1];
    JVM jvm = gson.fromJson(jvmMsg, JVM.class);
    Metric<JVM> avgThreadCpuTime = jvm.getAvgThreadCpuTime();
    setParent(jvm, avgThreadCpuTime);

    Metric<JVM> committedHeap = jvm.getCommittedHeap();
    setParent(jvm, committedHeap);

    Metric<JVM> usedHeap = jvm.getUsedHeap();
    setParent(jvm, usedHeap);

    Metric<JVM> gcOverhead = jvm.getGcOverhead();
    setParent(jvm, gcOverhead);

    Metric<JVM> threadsCount = jvm.getThreadsCount();
    setParent(jvm, threadsCount);

    ApplicationServer server = APMPrototype.getRoot().getAppServer();
    server.setRequests(requests);
    if (server.getJvm() == null)
        server.creatJVM(jvm.getName(), jvm.getVersion(), jvm.getArchitecture());

    JVM storedJvm = server.getJvm();
    storedJvm.setName(jvm.getName());
    storedJvm.setArchitecture(jvm.getArchitecture());
    storedJvm.setVersion(jvm.getVersion());

    mergeJVM(jvm, storedJvm);
}

From source file:com.denimgroup.threadfix.remote.response.ByteToStringSerializer.java

License:Mozilla Public License

@Override
public byte[] deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {
    return DatatypeConverter.parseBase64Binary(json.getAsString());
}

From source file:com.devamatre.core.JSONHelper.java

License:Open Source License

/**
 * /*ww  w .ja  va 2  s. c o  m*/
 * @param jsonObject
 * @param propertName
 * @return
 */
public static String valueForKey(JsonObject jsonObject, String propertName) {
    JsonElement jsonElement = jsonObject.get(propertName);
    return (jsonElement == null ? null : jsonElement.getAsString());
}

From source file:com.devamatre.core.JSONHelper.java

License:Open Source License

/**
 * // w  ww  . j a  v a 2  s  .  com
 * @param jsonObject
 * @param key
 * @return
 */
public static String getAsString(JsonObject jsonObject, String key) {
    JsonElement jsonElement = getElement(jsonObject, key);
    return (jsonElement != null ? jsonElement.getAsString() : null);
}

From source file:com.devicehive.json.adapters.RuntimeTypeAdapterFactory.java

License:Apache License

public <R> TypeAdapter<R> create(Gson gson, TypeToken<R> type) {
    if (type.getRawType() != baseType) {
        return null;
    }//from  w ww . ja v  a2s  .  c o  m

    final Map<String, TypeAdapter<?>> labelToDelegate = new LinkedHashMap<String, TypeAdapter<?>>();
    final Map<Class<?>, TypeAdapter<?>> subtypeToDelegate = new LinkedHashMap<Class<?>, TypeAdapter<?>>();
    for (Map.Entry<String, Class<?>> entry : labelToSubtype.entrySet()) {
        TypeAdapter<?> delegate = gson.getDelegateAdapter(this, TypeToken.get(entry.getValue()));
        labelToDelegate.put(entry.getKey(), delegate);
        subtypeToDelegate.put(entry.getValue(), delegate);
    }

    return new TypeAdapter<R>() {
        @Override
        public R read(JsonReader in) throws IOException {
            JsonElement jsonElement = Streams.parse(in);
            //                JsonElement labelJsonElement = jsonElement.getAsJsonObject().remove(typeFieldName);
            JsonElement labelJsonElement = jsonElement.getAsJsonObject().get(typeFieldName);
            if (labelJsonElement == null) {
                throw new JsonParseException("cannot deserialize " + baseType
                        + " because it does not define a field named " + typeFieldName);
            }
            String label = labelJsonElement.getAsString();
            @SuppressWarnings("unchecked") // registration requires that subtype extends T
            TypeAdapter<R> delegate = (TypeAdapter<R>) labelToDelegate.get(label);
            if (delegate == null) {
                throw new JsonParseException("cannot deserialize " + baseType + " subtype named " + label
                        + "; did you forget to register a subtype?");
            }
            return delegate.fromJsonTree(jsonElement);
        }

        @Override
        public void write(JsonWriter out, R value) throws IOException {
            Class<?> srcType = value.getClass();
            String label = subtypeToLabel.get(srcType);
            @SuppressWarnings("unchecked") // registration requires that subtype extends T
            TypeAdapter<R> delegate = (TypeAdapter<R>) subtypeToDelegate.get(srcType);
            if (delegate == null) {
                throw new JsonParseException(
                        "cannot serialize " + srcType.getName() + "; did you forget to register a subtype?");
            }
            JsonObject jsonObject = delegate.toJsonTree(value).getAsJsonObject();
            //                if (jsonObject.has(typeFieldName)) {
            //                    throw new JsonParseException("cannot serialize " + srcType.getName()
            //                            + " because it already defines a field named " + typeFieldName);
            //                }
            //                JsonObject clone = new JsonObject();
            //                clone.add(typeFieldName, new JsonPrimitive(label));
            //                for (Map.Entry<String, JsonElement> e : jsonObject.entrySet()) {
            //                    clone.add(e.getKey(), e.getValue());
            //                }
            //                Streams.write(clone, out);
            Streams.write(jsonObject, out);
        }
    }.nullSafe();
}

From source file:com.devicehive.websockets.WebSocketRequestProcessor.java

License:Apache License

private WebsocketAction getAction(JsonObject request) {
    JsonElement action = request.get(JsonMessageBuilder.ACTION);
    if (action == null || !action.isJsonPrimitive()) {
        return WebsocketAction.EMPTY;
    }// ww w.  ja va 2  s  .  co m
    return WebsocketAction.forName(action.getAsString());
}

From source file:com.diversityarrays.dalclient.DalUtil.java

License:Open Source License

/**
 * Convert the the input into a Map&lt;String,String&gt;.
 * @param input/*from  w w w. j av  a2  s.c  om*/
 * @return a Map&lt;String,String&gt;
 */
static private Map<String, String> asRowdata(JsonObject input) {
    Map<String, String> result = null;
    Set<Map.Entry<String, JsonElement>> entrySet = input.entrySet();
    if (entrySet != null && !entrySet.isEmpty()) {
        for (Map.Entry<String, JsonElement> entry : entrySet) {
            if (result == null) {
                result = new LinkedHashMap<>();
            }
            String key = entry.getKey();
            JsonElement value = entry.getValue();
            if (value == null || value.isJsonNull()) {
                result.put(key, "");
            } else {
                result.put(key, value.getAsString());
            }
        }
    }
    return result;
}

From source file:com.drguildo.bm.BookmarksManager.java

License:Open Source License

public static Bookmarks load() throws IOException {
    StringBuilder stringBuilder = new StringBuilder();

    if (!Files.exists(bookmarkPath)) {
        return bookmarks;
    }// w  w w.  j  a  va 2s. c  o  m

    try {
        BufferedReader bufferedReader = new BufferedReader(new FileReader(bookmarkFile));
        String string = bufferedReader.readLine();

        while (string != null) {
            stringBuilder.append(string);
            string = bufferedReader.readLine();
        }

        bufferedReader.close();
    } catch (IOException e) {
        e.printStackTrace();
        throw new IOException(e);
    }

    if (stringBuilder.length() == 0) {
        return bookmarks;
    }

    String json = stringBuilder.toString();

    JsonParser parser = new JsonParser();
    JsonArray array = parser.parse(json).getAsJsonArray();

    for (JsonElement element : array) {
        JsonObject jsonObject = element.getAsJsonObject();

        URL url = new URL(jsonObject.get("url").getAsString());

        Tags tags = new Tags();
        for (JsonElement tagElement : jsonObject.get("tags").getAsJsonArray()) {
            tags.add(tagElement.getAsString());
        }

        Date date = new Date(jsonObject.get("added").getAsLong());

        bookmarks.add(new Bookmark(url, tags, date));
    }

    return bookmarks;
}

From source file:com.dsh105.powermessage.core.PowerMessage.java

License:Open Source License

/**
 * Converts a raw JSON string to a PowerMessage object. This JSON string is in the format given by {@link #toJson()}
 * @param json the JSON string which represents a PowerMessage
 * @return A PowerMessage representing the given JSON string
 *///from   www  . ja  v a  2s.c  o m
public static PowerMessage fromJson(String json) {
    JsonArray serialised = jsonParser.parse(json).getAsJsonObject().getAsJsonArray("extra");
    PowerMessage powerMessage = new PowerMessage();

    for (JsonElement serialisedElement : serialised) {
        PowerSnippet snippet = new PowerSnippet("");
        JsonObject message = serialisedElement.getAsJsonObject();
        for (Map.Entry<String, JsonElement> entry : message.entrySet()) {
            String key = entry.getKey();
            JsonElement element = entry.getValue();

            if (key.equals("text")) {
                snippet.setText(element.getAsString());
            } else if (PowerSnippet.STYLE_TO_NAME_MAP.containsValue(key)) {
                if (element.getAsBoolean()) {
                    snippet.withColour(PowerSnippet.STYLE_TO_NAME_MAP.inverse().get(key));
                }
            } else if (key.equals("color")) {
                snippet.withColour(ChatColor.valueOf(element.getAsString().toUpperCase()));
            } else if (key.equals("clickEvent") || key.equals("hoverEvent")) {
                JsonObject event = element.getAsJsonObject();
                snippet.withEvent(key.substring(0, key.indexOf("Event")), event.get("action").getAsString(),
                        event.get("value").getAsString());
            }
        }
        powerMessage.then(snippet);
    }
    return powerMessage;
}

From source file:com.eclipsesource.connect.serialization.IdTypeAdapter.java

License:Open Source License

@Override
public Id deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {
    return new Id(json.getAsString());
}