Example usage for com.google.gson JsonPrimitive getAsString

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

Introduction

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

Prototype

@Override
public String getAsString() 

Source Link

Document

convenience method to get this element as a String.

Usage

From source file:adams.data.report.ReportJsonUtils.java

License:Open Source License

/**
 * Creates a report from the JSON object.
 *
 * @param jobj   the object to get the data from
 * @return      the report, null if failed to create or find data
 *//*from  ww  w.java 2 s. co m*/
public static Report fromJson(JsonObject jobj) {
    Report result;
    Field field;
    JsonPrimitive prim;

    result = new Report();
    for (Entry<String, JsonElement> entry : jobj.entrySet()) {
        prim = entry.getValue().getAsJsonPrimitive();
        if (prim.isBoolean()) {
            field = new Field(entry.getKey(), DataType.BOOLEAN);
            result.addField(field);
            result.setBooleanValue(field.getName(), prim.getAsBoolean());
        } else if (prim.isNumber()) {
            field = new Field(entry.getKey(), DataType.NUMERIC);
            result.addField(field);
            result.setNumericValue(field.getName(), prim.getAsNumber().doubleValue());
        } else {
            field = new Field(entry.getKey(), DataType.STRING);
            result.addField(field);
            result.setStringValue(field.getName(), prim.getAsString());
        }
    }

    return result;
}

From source file:angularBeans.remote.InvocationHandler.java

License:LGPL

private void update(Object o, JsonObject params) {

    if (params != null) {

        // boolean firstIn = false;

        for (Map.Entry<String, JsonElement> entry : params.entrySet()) {

            JsonElement value = entry.getValue();
            String name = entry.getKey();

            if ((name.equals("sessionUID")) || (name.equals("args"))) {
                continue;
            }//from   w  ww.  j  av  a2 s  . c  o m

            if ((value.isJsonObject()) && (!value.isJsonNull())) {

                String getName;
                try {
                    getName = CommonUtils.obtainGetter(o.getClass().getDeclaredField(name));

                    Method getter = o.getClass().getMethod(getName);

                    Object subObj = getter.invoke(o);

                    // logger.log(Level.INFO, "#entring sub object "+name);
                    update(subObj, value.getAsJsonObject());

                } catch (NoSuchFieldException | SecurityException | IllegalAccessException
                        | IllegalArgumentException | InvocationTargetException | NoSuchMethodException e) {

                    e.printStackTrace();
                }

            }
            // ------------------------------------
            if (value.isJsonArray()) {

                try {
                    String getter = CommonUtils.obtainGetter(o.getClass().getDeclaredField(name));

                    Method get = o.getClass().getDeclaredMethod(getter);

                    Type type = get.getGenericReturnType();
                    ParameterizedType pt = (ParameterizedType) type;
                    Type actType = pt.getActualTypeArguments()[0];

                    String className = actType.toString();

                    className = className.substring(className.indexOf("class") + 6);
                    Class clazz = Class.forName(className);

                    JsonArray array = value.getAsJsonArray();

                    Collection collection = (Collection) get.invoke(o);
                    Object elem;
                    for (JsonElement element : array) {
                        if (element.isJsonPrimitive()) {
                            JsonPrimitive primitive = element.getAsJsonPrimitive();

                            elem = element;
                            if (primitive.isBoolean())
                                elem = primitive.getAsBoolean();
                            if (primitive.isString()) {
                                elem = primitive.getAsString();
                            }
                            if (primitive.isNumber())
                                elem = primitive.isNumber();

                        } else {

                            elem = util.deserialise(clazz, element);
                        }

                        try {

                            if (collection instanceof List) {

                                if (collection.contains(elem))
                                    collection.remove(elem);
                            }

                            collection.add(elem);
                        } catch (UnsupportedOperationException e) {
                            Logger.getLogger("AngularBeans").log(java.util.logging.Level.WARNING,
                                    "trying to modify an immutable collection : " + name);
                        }

                    }

                } catch (Exception e) {
                    e.printStackTrace();

                }

            }

            // ------------------------------------------
            if (value.isJsonPrimitive() && (!name.equals("setSessionUID"))) {
                try {

                    if (!CommonUtils.hasSetter(o.getClass(), name)) {
                        continue;
                    }
                    name = "set" + name.substring(0, 1).toUpperCase() + name.substring(1);

                    Class type = null;
                    for (Method set : o.getClass().getDeclaredMethods()) {
                        if (CommonUtils.isSetter(set)) {
                            if (set.getName().equals(name)) {
                                Class<?>[] pType = set.getParameterTypes();

                                type = pType[0];
                                break;

                            }
                        }

                    }

                    if (type.equals(LobWrapper.class))
                        continue;

                    Object param = null;
                    if ((params.entrySet().size() >= 1) && (type != null)) {

                        param = CommonUtils.convertFromString(value.getAsString(), type);

                    }

                    o.getClass().getMethod(name, type).invoke(o, param);

                } catch (Exception e) {
                    e.printStackTrace();

                }
            }

        }
    }

}

From source file:at.ac.tuwien.infosys.jcloudscale.datastore.mapping.type.json.JsonEnumTypeAdapter.java

License:Apache License

@Override
public Enum deserialize(JsonElement element, TypeMetadata<JsonElement> typeMetadata) {
    JsonPrimitive jsonPrimitive = (JsonPrimitive) element;
    if (!jsonPrimitive.isString()) {
        throw new DatastoreException("Invalid value for enum type.");
    }//from  ww w  . j ava 2 s . co  m
    Class<? extends Enum> enumClass = (Class<? extends Enum>) typeMetadata.getFieldType();
    return Enum.valueOf(enumClass, jsonPrimitive.getAsString());
}

From source file:at.ac.tuwien.infosys.jcloudscale.datastore.mapping.type.json.JsonStringTypeAdapter.java

License:Apache License

@Override
public String deserialize(JsonElement element, TypeMetadata<JsonElement> typeMetadata) {
    JsonPrimitive jsonPrimitive = (JsonPrimitive) element;
    if (!jsonPrimitive.isString()) {
        throw new DatastoreException("Invalid value for string type.");
    }/*from   www.j a  v  a2s. c  o  m*/
    return jsonPrimitive.getAsString();
}

From source file:at.orz.arangodb.util.JsonUtils.java

License:Apache License

public static double toDouble(JsonElement elem) {
    if (elem != null && !elem.isJsonNull()) {
        JsonPrimitive primitive = elem.getAsJsonPrimitive();
        if (primitive.isNumber()) {
            return primitive.getAsDouble();
        } else if (primitive.isString()) {
            if ("INF".equals(primitive.getAsString())) {
                return Double.POSITIVE_INFINITY;
            } else if ("NaN".equals(primitive.getAsString())) {
                return Double.NaN;
            }//  www .  j av a  2  s  .  com
        }
    }
    return Double.NaN;
}

From source file:ca.ualberta.CMPUT301W15T06.GsonAdapter.java

License:Apache License

@Override
public T deserialize(JsonElement json, Type type, JsonDeserializationContext context)
        throws JsonParseException {
    // TODO Auto-generated method stub
    JsonObject jsonObject = json.getAsJsonObject();
    JsonPrimitive prim = (JsonPrimitive) jsonObject.get(CLASSNAME);
    String className = prim.getAsString();

    Class<?> klass = null;//from   w w w .  j av a2  s .  com
    try {
        klass = Class.forName(className);
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
        throw new JsonParseException(e.getMessage());
    }
    return context.deserialize(jsonObject.get(INSTANCE), klass);
}

From source file:ccm.pay2spawn.util.JsonNBTHelper.java

License:Open Source License

/**
 * There is no way to detect number types and NBT is picky about this. Lets hope the original type id is there, otherwise we are royally screwed.
 *//*from ww  w .  j  a  v a 2  s . c o  m*/
public static NBTBase parseJSON(JsonPrimitive element) {
    String string = element.getAsString();
    if (string.contains(":")) {
        for (int id = 0; id < NBTTypes.length; id++) {
            if (string.startsWith(NBTTypes[id] + ":")) {
                String value = string.replace(NBTTypes[id] + ":", "");
                value = RandomRegistry.solveRandom(id, value);
                switch (id) {
                // 0 = END
                case BYTE:
                    return new NBTTagByte(Byte.parseByte(value));
                case SHORT:
                    return new NBTTagShort(Short.parseShort(value));
                case INT:
                    return new NBTTagInt(Integer.parseInt(value));
                case LONG:
                    return new NBTTagLong(Long.parseLong(value));
                case FLOAT:
                    return new NBTTagFloat(Float.parseFloat(value));
                case DOUBLE:
                    return new NBTTagDouble(Double.parseDouble(value));
                case BYTE_ARRAY:
                    return parseJSONByteArray(value);
                case STRING:
                    return new NBTTagString(value);
                // 9 = LIST != JsonPrimitive
                // 10 = COMPOUND != JsonPrimitive
                case INT_ARRAY:
                    return parseJSONIntArray(value);
                }
            }
        }
    }

    // Now it becomes guesswork.
    if (element.isString())
        return new NBTTagString(string);
    if (element.isBoolean())
        return new NBTTagByte((byte) (element.getAsBoolean() ? 1 : 0));

    Number n = element.getAsNumber();
    if (n instanceof Byte)
        return new NBTTagByte(n.byteValue());
    if (n instanceof Short)
        return new NBTTagShort(n.shortValue());
    if (n instanceof Integer)
        return new NBTTagInt(n.intValue());
    if (n instanceof Long)
        return new NBTTagLong(n.longValue());
    if (n instanceof Float)
        return new NBTTagFloat(n.floatValue());
    if (n instanceof Double)
        return new NBTTagDouble(n.doubleValue());

    throw new NumberFormatException(element.toString() + " is was not able to be parsed.");
}

From source file:ccm.pay2spawn.util.JsonNBTHelper.java

License:Open Source License

public static JsonPrimitive fixNulls(JsonPrimitive primitive) {
    if (primitive.isBoolean())
        return new JsonPrimitive(primitive.getAsBoolean());
    if (primitive.isNumber())
        return new JsonPrimitive(primitive.getAsNumber());
    if (primitive.isString())
        return new JsonPrimitive(primitive.getAsString());
    return JSON_PARSER.parse(primitive.toString()).getAsJsonPrimitive();
}

From source file:ch.cern.db.flume.sink.elasticsearch.serializer.JSONtoElasticSearchEventSerializer.java

License:GNU General Public License

private void appendBody(XContentBuilder builder, Event event) throws IOException {
    JsonParser parser = new JsonParser();

    JsonObject json = parser.parse(new String(event.getBody())).getAsJsonObject();

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

        if (property.getValue().isJsonNull()) {
            builder.nullField(property.getKey());

            continue;
        }//from ww  w. ja  va2  s .c  o m

        if (!property.getValue().isJsonPrimitive()) {
            builder.field(property.getKey(), property.getValue());

            continue;
        }

        JsonPrimitive primitiveValue = (JsonPrimitive) property.getValue();

        if (primitiveValue.isBoolean())
            builder.field(property.getKey(), primitiveValue.getAsBoolean());
        else if (primitiveValue.isNumber())
            if (primitiveValue.getAsString().indexOf('.') != -1)
                builder.field(property.getKey(), primitiveValue.getAsNumber().doubleValue());
            else
                builder.field(property.getKey(), primitiveValue.getAsNumber().longValue());
        else if (primitiveValue.isString())
            builder.field(property.getKey(), primitiveValue.getAsString());
    }
}

From source file:ch.cyberduck.core.dropbox.DropboxExceptionMappingService.java

License:Open Source License

private void parse(final StringBuilder buffer, final String message) {
    final JsonParser parser = new JsonParser();
    try {//  w w w . ja  va2  s .c o m
        final JsonElement element = parser.parse(new StringReader(message));
        if (element.isJsonObject()) {
            final JsonObject json = element.getAsJsonObject();
            final JsonObject error = json.getAsJsonObject("error");
            if (null == error) {
                this.append(buffer, message);
            } else {
                final JsonPrimitive tag = error.getAsJsonPrimitive(".tag");
                if (null == tag) {
                    this.append(buffer, message);
                } else {
                    this.append(buffer, StringUtils.replace(tag.getAsString(), "_", " "));
                }
            }
        }
        if (element.isJsonPrimitive()) {
            this.append(buffer, element.getAsString());
        }
    } catch (JsonParseException e) {
        // Ignore
    }
}