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:net.nexustools.njs.JSON.java

License:Open Source License

public JSON(final Global global) {
    super(global);
    setHidden("stringify", new AbstractFunction(global) {

        public java.lang.String stringify(BaseObject object) {
            StringBuilder builder = new StringBuilder();
            stringify(object, builder);//from   w  w  w .j  a v a  2s  .co  m
            return builder.toString();
        }

        public void stringify(BaseObject object, StringBuilder builder) {
            if (Utilities.isUndefined(object)) {
                builder.append("null");
                return;
            }

            BaseObject toJSON = object.get("toJSON", OR_NULL);
            if (toJSON != null)
                stringify0(((BaseFunction) toJSON).call(object), builder);
            else
                stringify0(object, builder);
        }

        public void stringify0(BaseObject object, StringBuilder builder) {
            if (object instanceof GenericArray) {
                builder.append('[');
                if (((GenericArray) object).length() > 0) {
                    stringify(object.get(0), builder);
                    for (int i = 1; i < ((GenericArray) object).length(); i++) {
                        builder.append(',');
                        stringify(object.get(i), builder);
                    }
                }
                builder.append(']');
            } else if (object instanceof String.Instance) {
                builder.append('"');
                builder.append(object.toString());
                builder.append('"');
            } else if (object instanceof Number.Instance) {
                double number = ((Number.Instance) object).value;
                if (Double.isNaN(number) || Double.isInfinite(number))
                    builder.append("null");

                builder.append(object.toString());
            } else if (object instanceof Boolean.Instance)
                builder.append(object.toString());
            else {
                builder.append('{');
                Iterator<java.lang.String> it = object.keys().iterator();
                if (it.hasNext()) {

                    java.lang.String key = it.next();
                    builder.append('"');
                    builder.append(key);
                    builder.append("\":");
                    stringify(object.get(key), builder);

                    if (it.hasNext()) {
                        do {
                            builder.append(',');
                            key = it.next();
                            builder.append('"');
                            builder.append(key);
                            builder.append("\":");
                            stringify(object.get(key), builder);
                        } while (it.hasNext());
                    }
                }
                builder.append('}');
            }
        }

        @Override
        public BaseObject call(BaseObject _this, BaseObject... params) {
            switch (params.length) {
            case 0:
                return Undefined.INSTANCE;

            case 1:
                if (params[0] == Undefined.INSTANCE)
                    return Undefined.INSTANCE;
                return global.wrap(stringify(params[0]));

            default:
                return global.wrap("undefined");
            }
        }

        @Override
        public java.lang.String name() {
            return "JSON_stringify";
        }
    });
    setHidden("parse", new AbstractFunction(global) {
        final Gson GSON;
        {
            GsonBuilder gsonBuilder = new GsonBuilder();
            gsonBuilder.registerTypeAdapter(BaseObject.class, new JsonDeserializer<BaseObject>() {
                @Override
                public BaseObject deserialize(JsonElement je, Type type, JsonDeserializationContext jdc)
                        throws JsonParseException {
                    if (je.isJsonNull())
                        return Null.INSTANCE;
                    if (je.isJsonPrimitive()) {
                        JsonPrimitive primitive = je.getAsJsonPrimitive();
                        if (primitive.isBoolean())
                            return primitive.getAsBoolean() ? global.Boolean.TRUE : global.Boolean.FALSE;
                        if (primitive.isNumber())
                            return global.wrap(primitive.getAsDouble());
                        if (primitive.isString())
                            return global.wrap(primitive.getAsString());
                        throw new UnsupportedOperationException(primitive.toString());
                    }
                    if (je.isJsonObject()) {
                        GenericObject go = new GenericObject(global);
                        JsonObject jo = je.getAsJsonObject();
                        for (Map.Entry<java.lang.String, JsonElement> entry : jo.entrySet()) {
                            go.set(entry.getKey(), deserialize(entry.getValue(), type, jdc));
                        }
                        return go;
                    }
                    if (je.isJsonArray()) {
                        JsonArray ja = je.getAsJsonArray();
                        BaseObject[] array = new BaseObject[ja.size()];
                        for (int i = 0; i < array.length; i++) {
                            array[i] = deserialize(ja.get(i), type, jdc);
                        }
                        return new GenericArray(global, array);
                    }
                    throw new UnsupportedOperationException(je.toString());
                }
            });
            GSON = gsonBuilder.create();
        }

        @Override
        public BaseObject call(BaseObject _this, BaseObject... params) {
            try {
                return GSON.fromJson(params[0].toString(), BaseObject.class);
            } catch (com.google.gson.JsonSyntaxException ex) {
                throw new Error.JavaException("SyntaxError", "Unexpected token", ex);
            }
        }

        @Override
        public java.lang.String name() {
            return "JSON_parse";
        }
    });
}

From source file:net.oauth.jsontoken.JsonToken.java

License:Apache License

private Long getParamAsLong(String param) {
    JsonPrimitive primitive = getParamAsPrimitive(param);
    if (primitive != null && (primitive.isNumber() || primitive.isString())) {
        try {//w  w w .j av a  2 s  .co  m
            return primitive.getAsLong();
        } catch (NumberFormatException e) {
            return null;
        }
    }
    return null;
}

From source file:net.praqma.tracey.tracey_rabbitmq_neo4j_bridge.Tracey2Neo.java

private Object getPrimitiveType(JsonElement jo) {
    if (!jo.isJsonPrimitive()) {
        return null;
    }/*from   ww  w . j av a  2s  .  c o  m*/
    JsonPrimitive jp = jo.getAsJsonPrimitive();
    if (jp.isBoolean()) {
        return jp.getAsBoolean();
    }
    if (jp.isNumber()) {
        return jp.getAsNumber();
    }
    if (jp.isString()) {
        return jp.getAsString();
    }
    return null;
}

From source file:org.apache.airavata.common.utils.JSONUtil.java

License:Apache License

private static boolean isEqual(JsonPrimitive primitiveOrig, JsonPrimitive primitiveNew) {
    if (primitiveOrig == null && primitiveNew == null) {
        return true;
    } else if (primitiveOrig == null || primitiveNew == null) {
        return false;
    } else {//from  w  w w . ja v a2 s.  com
        if (primitiveOrig.isString() && primitiveNew.isString()) {
            if (!primitiveOrig.getAsString().equals(primitiveNew.getAsString())) {
                return false;
            }
        } else if (primitiveOrig.isBoolean() && primitiveNew.isBoolean()) {
            if ((Boolean.valueOf(primitiveOrig.getAsBoolean()).compareTo(primitiveNew.getAsBoolean()) != 0)) {
                return false;
            }
        } else if (primitiveOrig.isNumber() && primitiveNew.isNumber()) {
            if (new Double(primitiveOrig.getAsDouble()).compareTo(primitiveNew.getAsDouble()) != 0) {
                return false;
            }
        } else {
            return primitiveOrig.isJsonNull() && primitiveNew.isJsonNull();
        }
    }
    return true;
}

From source file:org.apache.hadoop.hive.json.JsonShredder.java

License:Apache License

private void shredObject(String name, JsonElement json) throws IOException {
    if (json.isJsonPrimitive()) {
        JsonPrimitive primitive = (JsonPrimitive) json;
        if (primitive.isBoolean()) {
            getFile(name).append(primitive.getAsBoolean() + "\n");
        } else if (primitive.isString()) {
            getFile(name).append(primitive.getAsString().replace("\\", "\\\\").replace("\n", "\\n") + "\n");
        } else if (primitive.isNumber()) {
            getFile(name).append(primitive.getAsNumber() + "\n");
        }/*from ww  w .j av a 2 s.  com*/
    } else if (json.isJsonNull()) {
        // just skip it
    } else if (json.isJsonArray()) {
        for (JsonElement child : ((JsonArray) json)) {
            shredObject(name, child);
        }
    } else {
        JsonObject obj = (JsonObject) json;
        for (Map.Entry<String, JsonElement> field : obj.entrySet()) {
            String fieldName = field.getKey();
            shredObject(name + "." + fieldName, field.getValue());
        }
    }
}

From source file:org.apache.qpid.disttest.json.PropertyValueAdapter.java

License:Apache License

@Override
public PropertyValue deserialize(JsonElement json, Type type, JsonDeserializationContext context)
        throws JsonParseException {
    if (json.isJsonNull()) {
        return null;
    } else if (json.isJsonPrimitive()) {
        Object result = null;//from w  w  w  . j av  a2s.  c  o m
        JsonPrimitive primitive = json.getAsJsonPrimitive();
        if (primitive.isString()) {
            result = primitive.getAsString();
        } else if (primitive.isNumber()) {
            String asString = primitive.getAsString();
            if (asString.indexOf('.') != -1 || asString.indexOf('e') != -1) {
                result = primitive.getAsDouble();
            } else {
                result = primitive.getAsLong();
            }
        } else if (primitive.isBoolean()) {
            result = primitive.getAsBoolean();
        } else {
            throw new JsonParseException("Unsupported primitive value " + primitive);
        }
        return new SimplePropertyValue(result);
    } else if (json.isJsonArray()) {
        JsonArray array = json.getAsJsonArray();
        List<Object> result = new ArrayList<Object>(array.size());
        for (JsonElement element : array) {
            result.add(context.deserialize(element, Object.class));
        }
        return new SimplePropertyValue(result);
    } else if (json.isJsonObject()) {
        JsonObject object = json.getAsJsonObject();
        JsonElement defElement = object.getAsJsonPrimitive(DEF_FIELD);
        Class<?> classInstance = null;
        if (defElement != null) {
            try {
                classInstance = _factory.getPropertyValueClass(defElement.getAsString());
            } catch (ClassNotFoundException e) {
                // ignore
            }
        }
        if (classInstance == null) {
            Map<String, Object> result = new HashMap<String, Object>();
            for (Map.Entry<String, JsonElement> entry : object.entrySet()) {
                Object value = context.deserialize(entry.getValue(), Object.class);
                result.put(entry.getKey(), value);
            }
            return new SimplePropertyValue(result);
        } else {
            return context.deserialize(json, classInstance);
        }
    } else {
        throw new JsonParseException("Unsupported JSON type " + json);
    }
}

From source file:org.apache.sling.jms.Json.java

License:Apache License

private static <T> T toMapValue(JsonPrimitive p) {
    if (p.isString()) {
        return (T) p.getAsString();
    } else if (p.isBoolean()) {
        return (T) ((Boolean) p.getAsBoolean());
    } else if (p.isNumber()) {
        double d = p.getAsDouble();
        if (Math.floor(d) == d) {
            return (T) ((Long) p.getAsLong());
        }/*  ww  w  .j ava 2  s . c o  m*/
        return (T) ((Double) d);
    } else {
        return null;
    }
}

From source file:org.cvasilak.jboss.mobile.app.model.ManagementModelBase.java

License:Apache License

public void setValue(JsonElement value) {
    if (value instanceof JsonPrimitive) {
        JsonPrimitive primitive = (JsonPrimitive) value;

        if (primitive.isNumber()) {
            try {
                this.value = NumberFormat.getInstance().parse(primitive.getAsString());
            } catch (ParseException e) {
            }/*from ww w. j  av a 2  s  .com*/
        } else if (primitive.isBoolean()) {
            this.value = primitive.getAsBoolean();
        } else if (primitive.isString()) {
            this.value = primitive.getAsString();
        }

    } else if (value instanceof JsonNull) {
        this.value = "undefined";

    } else if (value instanceof JsonArray) {
        List<String> list = new ArrayList<String>();

        Iterator<JsonElement> iterator = value.getAsJsonArray().iterator();

        while (iterator.hasNext()) {
            JsonElement elem = iterator.next();

            if (elem instanceof JsonObject)
                list.add(elem.toString());
            else
                list.add(elem.getAsString());
        }

        this.value = list;

    } else if (value instanceof JsonObject) {
        this.value = value.toString();
    }
}

From source file:org.cvasilak.jboss.mobile.app.model.OperationParameter.java

License:Apache License

public void setDefaultValue(JsonElement value) {
    if (value instanceof JsonPrimitive) {
        JsonPrimitive primitive = (JsonPrimitive) value;

        if (primitive.isNumber()) {
            try {
                this.defaultValue = NumberFormat.getInstance().parse(primitive.getAsString());
            } catch (ParseException e) {
            }//from   w  w w . j ava2s  .co m
        } else if (primitive.isBoolean()) {
            this.defaultValue = primitive.getAsBoolean();
        } else if (primitive.isString()) {
            this.defaultValue = primitive.getAsString();
        }
    }
}

From source file:org.dashbuilder.dataprovider.backend.elasticsearch.rest.client.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 formatted value for the given column type.
 *///  w  w  w.  j  a v a 2s .c  o  m
public static Object parseValue(ElasticSearchDataSetDef definition, ElasticSearchDataSetMetadata metadata,
        DataColumn column, JsonElement valueElement) {
    if (column == null || valueElement == null || valueElement.isJsonNull())
        return null;
    if (!valueElement.isJsonPrimitive())
        throw new RuntimeException("Not expected JsonElement type to parse from query response.");

    JsonPrimitive valuePrimitive = valueElement.getAsJsonPrimitive();

    ColumnType columnType = column.getColumnType();

    if (ColumnType.NUMBER.equals(columnType)) {

        return valueElement.getAsDouble();

    } 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()) {

            DateTimeFormatter formatter = null;
            String datePattern = metadata.getFieldPattern(column.getId());
            if (datePattern == null || datePattern.trim().length() == 0) {
                // If no custom pattern for date field, use the default by EL -> org.joda.time.format.ISODateTimeFormat#dateOptionalTimeParser
                formatter = ElasticSearchDataSetProvider.EL_DEFAULT_DATETIME_FORMATTER;
            } else {
                // Obtain the date value by parsing using the EL pattern specified for this field.
                formatter = DateTimeFormat.forPattern(datePattern);
            }

            DateTime dateTime = formatter.parseDateTime(valuePrimitive.getAsString());
            return dateTime.toDate();
        }

        if (valuePrimitive.isNumber()) {

            return new Date(valuePrimitive.getAsLong());

        }

        throw new UnsupportedOperationException(
                "Value core type not supported. Expecting string or number when using date core field types.");

    }

    // LABEL, TEXT or grouped DATE column types.
    String valueAsString = valueElement.getAsString();
    ColumnGroup columnGroup = column.getColumnGroup();

    // For FIXED date values, remove the unnecessary "0" at first character. (eg: replace month "01" to "1")
    if (columnGroup != null && GroupStrategy.FIXED.equals(columnGroup.getStrategy())
            && valueAsString.startsWith("0"))
        return valueAsString.substring(1);

    return valueAsString;
}