Example usage for com.google.gson JsonPrimitive isString

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

Introduction

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

Prototype

public boolean isString() 

Source Link

Document

Check whether this primitive contains a String value.

Usage

From source file:org.dashbuilder.dataprovider.backend.elasticsearch.rest.impl.jest.ElasticSearchJestClient.java

License:Apache License

/**
 * Parses a given value (for a given column type) returned by response JSON query body from EL server.
 *
 * @param column       The data column definition.
 * @param valueElement The value element from JSON query response to format.
 * @return The object value for the given column type.
 *//*ww  w.  j  a  va 2 s  .  c o m*/
public Object parseValue(DataSetMetadata metadata, DataColumn column, JsonElement valueElement)
        throws ParseException {
    if (column == null || valueElement == null || valueElement.isJsonNull())
        return null;
    if (!valueElement.isJsonPrimitive())
        throw new RuntimeException("Not expected JsonElement type to parse from query response.");

    ElasticSearchDataSetDef def = (ElasticSearchDataSetDef) metadata.getDefinition();
    JsonPrimitive valuePrimitive = valueElement.getAsJsonPrimitive();
    ColumnType columnType = column.getColumnType();

    if (ColumnType.TEXT.equals(columnType)) {
        return typeMapper.parseText(def, column.getId(), valueElement.getAsString());
    } else if (ColumnType.LABEL.equals(columnType)) {
        boolean isColumnGroup = column.getColumnGroup() != null
                && column.getColumnGroup().getStrategy().equals(GroupStrategy.FIXED);
        return typeMapper.parseLabel(def, column.getId(), valueElement.getAsString(), isColumnGroup);

    } else if (ColumnType.NUMBER.equals(columnType)) {
        return typeMapper.parseNumeric(def, column.getId(), valueElement.getAsString());

    } else if (ColumnType.DATE.equals(columnType)) {

        // We can expect two return core types from EL server when handling dates:
        // 1.- String type, using the field pattern defined in the index' mappings, when it's result of a query without aggregations.
        // 2.- Numeric type, when it's result from a scalar function or a value pickup.

        if (valuePrimitive.isString()) {
            return typeMapper.parseDate(def, column.getId(), valuePrimitive.getAsString());
        }

        if (valuePrimitive.isNumber()) {
            return typeMapper.parseDate(def, column.getId(), valuePrimitive.getAsLong());
        }

    }

    throw new UnsupportedOperationException("Cannot parse value for column with id [" + column.getId()
            + "] (Data Set UUID [" + def.getUUID()
            + "]). Value core type not supported. Expecting string or number or date core field types.");

}

From source file:org.debux.webmotion.server.call.ClientSession.java

License:Open Source License

/**
 * Return only JsonElement use getAttribute and getAttributes with class as 
 * parameter to get a value./* ww w. jav a2  s.c  o  m*/
 */
@Override
public Object getAttribute(String name) {
    JsonElement value = attributes.get(name);
    if (value == null) {
        return value;

    } else if (value.isJsonPrimitive()) {
        JsonPrimitive primitive = value.getAsJsonPrimitive();
        if (primitive.isString()) {
            return primitive.getAsString();

        } else if (primitive.isBoolean()) {
            return primitive.getAsBoolean();

        } else if (primitive.isNumber()) {
            return primitive.getAsDouble();
        }

    } else if (value.isJsonArray()) {
        return value.getAsJsonArray();

    } else if (value.isJsonObject()) {
        return value.getAsJsonObject();

    } else if (value.isJsonNull()) {
        return value.getAsJsonNull();
    }
    return value;
}

From source file:org.devnexus.aerogear.ShadowStore.java

License:Apache License

private void saveElement(JsonObject serialized, String path, Serializable id) {
    String sql = String.format(
            "insert into shadow_%s_property (PROPERTY_NAME, PROPERTY_VALUE, PARENT_ID) values (?,?,?)",
            className);//w  w  w .j a  v a  2  s  .c o  m
    Set<Map.Entry<String, JsonElement>> members = serialized.entrySet();
    String pathVar = path.isEmpty() ? "" : ".";
    for (Map.Entry<String, JsonElement> member : members) {
        JsonElement jsonValue = member.getValue();
        String propertyName = member.getKey();
        if (jsonValue.isJsonObject()) {
            saveElement((JsonObject) jsonValue, path + pathVar + propertyName, id);
        } else if (jsonValue.isJsonArray()) {
            JsonArray jsonArray = jsonValue.getAsJsonArray();
            for (int index = 0; index < jsonArray.size(); index++) {
                JsonElement arrayElement = jsonArray.get(index);
                if (arrayElement.isJsonPrimitive()) {
                    JsonPrimitive primitive = arrayElement.getAsJsonPrimitive();
                    if (primitive.isBoolean()) {
                        String value = primitive.getAsBoolean() ? "true" : "false";
                        getDatabase().execSQL(sql, new Object[] {
                                path + pathVar + propertyName + String.format("[%d]", index), value, id });
                    } else if (primitive.isNumber()) {
                        Number value = primitive.getAsNumber();
                        getDatabase().execSQL(sql, new Object[] {
                                path + pathVar + propertyName + String.format("[%d]", index), value, id });
                    } else if (primitive.isString()) {
                        String value = primitive.getAsString();
                        getDatabase().execSQL(sql, new Object[] {
                                path + pathVar + propertyName + String.format("[%d]", index), value, id });
                    } else {
                        throw new IllegalArgumentException(
                                arrayElement + " isn't a number, boolean, or string");
                    }

                } else {
                    saveElement(arrayElement.getAsJsonObject(),
                            path + pathVar + propertyName + String.format("[%d]", index), id);
                }

            }
        } else {
            if (jsonValue.isJsonPrimitive()) {
                JsonPrimitive primitive = jsonValue.getAsJsonPrimitive();
                if (primitive.isBoolean()) {
                    String value = primitive.getAsBoolean() ? "true" : "false";
                    getDatabase().execSQL(sql, new Object[] { path + pathVar + propertyName, value, id });
                } else if (primitive.isNumber()) {
                    Number value = primitive.getAsNumber();
                    getDatabase().execSQL(sql, new Object[] { path + pathVar + propertyName, value, id });
                } else if (primitive.isString()) {
                    String value = primitive.getAsString();
                    getDatabase().execSQL(sql, new Object[] { path + pathVar + propertyName, value, id });
                } else {
                    throw new IllegalArgumentException(jsonValue + " isn't a number, boolean, or string");
                }

            } else {
                throw new IllegalArgumentException(jsonValue + " isn't a JsonPrimitive");
            }

        }
    }
}

From source file:org.devnexus.aerogear.ShadowStore.java

License:Apache License

private void buildKeyValuePairs(JsonObject where, List<Pair<String, String>> keyValues, String parentPath) {
    Set<Map.Entry<String, JsonElement>> keys = where.entrySet();
    String pathVar = parentPath.isEmpty() ? "" : ".";//Set a dot if parent path is not empty
    for (Map.Entry<String, JsonElement> entry : keys) {
        String key = entry.getKey();
        String path = parentPath + pathVar + key;
        JsonElement jsonValue = entry.getValue();
        if (jsonValue.isJsonObject()) {
            buildKeyValuePairs((JsonObject) jsonValue, keyValues, path);
        } else {//from w ww.java2 s.  com
            if (jsonValue.isJsonPrimitive()) {
                JsonPrimitive primitive = jsonValue.getAsJsonPrimitive();
                if (primitive.isBoolean()) {
                    String value = primitive.getAsBoolean() ? "true" : "false";
                    keyValues.add(new Pair<String, String>(path, value));
                } else if (primitive.isNumber()) {
                    Number value = primitive.getAsNumber();
                    keyValues.add(new Pair<String, String>(path, value.toString()));
                } else if (primitive.isString()) {
                    String value = primitive.getAsString();
                    keyValues.add(new Pair<String, String>(path, value));
                } else {
                    throw new IllegalArgumentException(jsonValue + " isn't a number, boolean, or string");
                }

            } else {
                throw new IllegalArgumentException(jsonValue + " isn't a JsonPrimitive");
            }

        }
    }
}

From source file:org.eclim.Eclim.java

License:Open Source License

public static Object toType(JsonElement json) {
    // null/*from  w w w . ja v  a  2  s . com*/
    if (json.isJsonNull()) {
        return null;

        // int, double, boolean, String
    } else if (json.isJsonPrimitive()) {
        JsonPrimitive prim = json.getAsJsonPrimitive();
        if (prim.isBoolean()) {
            return prim.getAsBoolean();
        } else if (prim.isString()) {
            return prim.getAsString();
        } else if (prim.isNumber()) {
            if (prim.getAsString().indexOf('.') != -1) {
                return prim.getAsDouble();
            }
            return prim.getAsInt();
        }

        // List
    } else if (json.isJsonArray()) {
        ArrayList<Object> type = new ArrayList<Object>();
        for (JsonElement element : json.getAsJsonArray()) {
            type.add(toType(element));
        }
        return type;

        // Map
    } else if (json.isJsonObject()) {
        HashMap<String, Object> type = new HashMap<String, Object>();
        for (Map.Entry<String, JsonElement> entry : json.getAsJsonObject().entrySet()) {
            type.put(entry.getKey(), toType(entry.getValue()));
        }
        return type;
    }

    return null;
}

From source file:org.eclipse.che.api.core.jsonrpc.impl.GsonJsonRpcUnmarshaller.java

License:Open Source License

private Object getInnerItem(JsonElement jsonElement) {
    if (jsonElement.isJsonNull()) {
        return null;
    }/*  www  . ja  v a 2  s .  c om*/

    if (jsonElement.isJsonObject()) {
        return jsonElement.getAsJsonObject();
    }

    if (jsonElement.isJsonPrimitive()) {
        JsonPrimitive jsonPrimitive = jsonElement.getAsJsonPrimitive();
        if (jsonPrimitive.isNumber()) {
            return jsonPrimitive.getAsDouble();
        } else if (jsonPrimitive.isString()) {
            return jsonPrimitive.getAsString();
        } else {
            return jsonPrimitive.getAsBoolean();
        }
    }

    throw new IllegalStateException("Unexpected json element type");
}

From source file:org.eclipse.leshan.server.demo.servlet.json.LwM2mNodeDeserializer.java

License:Open Source License

private org.eclipse.leshan.core.model.ResourceModel.Type getTypeFor(JsonPrimitive val) {
    if (val.isBoolean())
        return org.eclipse.leshan.core.model.ResourceModel.Type.BOOLEAN;
    if (val.isString())
        return org.eclipse.leshan.core.model.ResourceModel.Type.STRING;
    if (val.isNumber()) {
        if (val.getAsDouble() == val.getAsLong()) {
            return org.eclipse.leshan.core.model.ResourceModel.Type.INTEGER;
        } else {//from www .  j  a  v a  2  s  .  c  o  m
            return org.eclipse.leshan.core.model.ResourceModel.Type.FLOAT;
        }
    }
    // use string as default value
    return org.eclipse.leshan.core.model.ResourceModel.Type.STRING;
}

From source file:org.eclipse.leshan.standalone.servlet.json.LwM2mNodeDeserializer.java

License:Open Source License

private Value<?> deserializeValue(JsonPrimitive val) {
    Value<?> value = null;//from  ww w  . j  av  a2s .  c  om
    if (val.isNumber()) {

        Number n = val.getAsNumber();
        if (n.doubleValue() == (long) n.doubleValue()) {
            Long lValue = Long.valueOf(n.longValue());
            if (lValue >= Integer.MIN_VALUE && lValue <= Integer.MAX_VALUE) {
                value = Value.newIntegerValue(lValue.intValue());
            } else {
                value = Value.newLongValue(lValue);
            }
        } else {
            Double dValue = Double.valueOf(n.doubleValue());
            if (dValue >= Float.MIN_VALUE && dValue <= Float.MAX_VALUE) {
                value = Value.newFloatValue(dValue.floatValue());
            } else {
                value = Value.newDoubleValue(dValue);
            }
        }

    } else if (val.isBoolean()) {
        value = Value.newBooleanValue(val.getAsBoolean());
    } else if (val.isString()) {
        value = Value.newStringValue(val.getAsString());
    }
    return value;
}

From source file:org.eclipse.milo.opcua.binaryschema.gson.JsonStructureCodec.java

License:Open Source License

@Override
protected Object memberTypeToOpcUaScalar(JsonElement member, String typeName) {
    if (member == null || member.isJsonNull()) {
        return null;
    } else if (member.isJsonArray()) {
        JsonArray array = member.getAsJsonArray();

        switch (typeName) {
        case "ByteString": {
            byte[] bs = new byte[array.size()];

            for (int i = 0; i < array.size(); i++) {
                bs[i] = array.get(i).getAsByte();
            }//from ww w. jav a 2 s .co m

            return ByteString.of(bs);
        }

        default:
            return array;
        }
    } else if (member.isJsonObject()) {
        JsonObject jsonObject = member.getAsJsonObject();

        switch (typeName) {
        case "QualifiedName": {
            return new QualifiedName(jsonObject.get("namespaceIndex").getAsInt(),
                    jsonObject.get("name").getAsString());
        }
        case "LocalizedText": {
            return new LocalizedText(jsonObject.get("locale").getAsString(),
                    jsonObject.get("text").getAsString());
        }

        default:
            return jsonObject;
        }
    } else if (member.isJsonPrimitive()) {
        JsonPrimitive primitive = member.getAsJsonPrimitive();

        if (primitive.isBoolean()) {
            return primitive.getAsBoolean();
        } else if (primitive.isString()) {
            switch (typeName) {
            case "Guid":
                return UUID.fromString(primitive.getAsString());

            case "NodeId":
                return NodeId.parseSafe(primitive.getAsString()).orElse(NodeId.NULL_VALUE);

            case "ExpandedNodeId":
                return ExpandedNodeId.parse(primitive.getAsString());

            case "XmlElement":
                return new XmlElement(primitive.getAsString());

            default:
                return primitive.getAsString();
            }
        } else if (primitive.isNumber()) {
            switch (typeName) {
            case "SByte":
                return primitive.getAsByte();
            case "Int16":
                return primitive.getAsShort();
            case "Int32":
                return primitive.getAsInt();
            case "Int64":
                return primitive.getAsLong();

            case "Byte":
                return ubyte(primitive.getAsShort());
            case "UInt16":
                return ushort(primitive.getAsInt());
            case "UInt32":
                return uint(primitive.getAsLong());
            case "UInt64":
                return ulong(primitive.getAsBigInteger());

            case "Float":
                return primitive.getAsFloat();
            case "Double":
                return primitive.getAsDouble();

            case "DateTime":
                return new DateTime(primitive.getAsLong());

            case "StatusCode":
                return new StatusCode(primitive.getAsLong());

            default:
                return primitive.getAsNumber();
            }
        }
    }

    return null;
}

From source file:org.eclipse.smarthome.automation.parser.gson.internal.ConfigurationDeserializer.java

License:Open Source License

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

    Configuration configuration = new Configuration();
    JsonObject jo = (JsonObject) json;//from  w  w  w  . j av  a  2  s  .  co  m
    for (Entry<String, JsonElement> e : jo.entrySet()) {
        JsonPrimitive value = e.getValue().getAsJsonPrimitive();
        if (value.isString()) {
            configuration.put(e.getKey(), value.getAsString());
        } else if (value.isNumber()) {
            configuration.put(e.getKey(), value.getAsBigDecimal());
        } else if (value.isBoolean()) {
            configuration.put(e.getKey(), value.getAsBoolean());
        }
    }
    return configuration;
}